Search code examples
c#sitecoresitecore-workflow

Sitecore: Assign workflow to an item programmatically


I have configured a workflow, starts with "Draft" state as usual. And I have configured the workflow for standard values of the template. It works perfect in Content editor. (When I create an item using the content editor, once I create the item, Workflow gets assigned to the item and it's state becomes "Draft".)

But when I create an item programmatically under the above template it does not assign the workflow. What should I do to assign workflow? Please share any code samples if you have.

Thanks.

Sitecore.Data.Items.TemplateItem template = this.MasterDatabase.GetItem("/sitecore/templates/user defined/sample types");
Sitecore.Data.Items.Item parent = this.MasterDatabase.GetItem(parentId); 

Sitecore.Data.Items.Item newItem;                
// Create new item and retrieve it
newItem = template.CreateItemFrom("sampleName", parent);

newItem.Editing.BeginEdit();

newItem.Name = StringFormatter.CreateItemNameFromID(this.newItem);
newItem.Fields["Title"].Value = "Sample Title"

newItem.Editing.EndEdit();

Solution

  • Solved the issue with Standard Fields,

    newItem.Editing.BeginEdit();                    
    newItem.Fields["__Workflow"].Value = "{4D1F00EF-CA5D-4F36-A51E-E77E2BAE4A24}"; //Set workflow
    newItem.Fields["__Workflow state"].Value = "{7F39DF46-B4B9-4D08-A0D4-32DE6FD643D1}"; //Set   workflow state to Unposted.
    newClassified.Editing.EndEdit();