Associating Workflows with Lists

There are two ways to associate a workflow with a list in SharePoint. One way is to use the SharePoint user interface. For this option, some workflows provide specific association forms that capture specific information that the workflow requires. You can also programmatically perform the association. For information about how to do this, see Using Custom Field Types and Field Controls, which uses the Training Management application as an example.

For the Training Management application, a SharePoint feature receiver associates the registration approval workflow with the registration list. The association occurs when the ContosoTrainingManagementRegistrationApprovalAssociation_v1 feature is activated. Programmatically associating a workflow with a list requires the following components:

  • A workflow template
  • A task list
  • A workflow history list
  • The list instance that will be associated with the workflow

The Training Management application retrieves the registration list, the registration approval task list, and the workflow history list that are defined in the ContosoTrainingManagementWeb SharePoint feature. The following code from the Training Management application demonstrates how to do this.

SPList taskList = web.Lists[Lists.RegistrationApprovalTasks];
SPList historyList = web.Lists[Lists.WorkflowHistory];
SPList registrationList = web.Lists[Lists.Registrations];

After the lists are retrieved, the SPWorkflowManager class retrieves the course registration approval workflow template. You must specify the task list and workflow history list that are used by the workflow association. The last step is to add the workflow association to the registration list and enable the workflow. The following code from the Training Management application demonstrates how to do this.

var existingAssociation = registrationList.WorkflowAssociations.GetAssociationByName(WorkflowTemplates.RegistrationApprovalName_v1, CultureInfo.CurrentCulture);
if (existingAssociation == null)
{
    // Create a worklow manager and associate the Course Registration 
    // Approval Workflow template to our Registrations list.
    SPWorkflowManager workflowManager = web.Site.WorkflowManager;
    SPWorkflowTemplateCollection templates = workflowManager.GetWorkflowTemplatesByCategory(web, null);
    SPWorkflowTemplate template = templates.GetTemplateByBaseID(new Guid(WorkflowTemplates.RegistrationApprovalBaseId_v1));
    SPWorkflowAssociation association = SPWorkflowAssociation.CreateListAssociation(template, template.Name, taskList, historyList);
    association.AllowManual = true;
    association.AutoStartCreate = true;
    registrationList.AddWorkflowAssociation(association);
    registrationList.Update();
    association.Enabled = true;
}

Home page on MSDN | Community site