Wednesday, May 7, 2008

How to programatically associate a workflow with a list

I needed to do this in a previous project where we created a custom workflow and needed to associate that workflow with a list that existed within a SharePoint site.

We used a site definition that provisioned a pages library, and activated the workflow feature each time a site was created.

However it was still a manual step to associate the workflow with the pages library. To solve this we created a site feature receiver that ran when the site was created and called the following code.


 
public override void FeatureActivated(SPFeatureReceiverProperties properties)
{
using (SPWeb siteWeb = (SPWeb)properties.Feature.Parent)
{
SPList list = siteWeb.Lists["Name here"];
SPWorkflowTemplate baseTemplate =
siteWeb.WorkflowTemplates["Workflow Guid"];

SPWorkflowAssociation assoc = SPWorkflowAssociation.CreateListAssociation(
baseTemplate
, "NameOfWorkflow"
, "SPList task list"
, "SPList history list");

list.AddWorkflowAssociation(assoc);
}
}

No comments: