Create Item in Sitecore programmatically with workflow assigned

Posted 07/18/2016 by Yogeshwer Sharma

There are many post already found on the internet where we can find API’s for creating an item in Sitecore.  But I am writing this I found something interesting, may be it is very common but it was something new for me. 

I was working on a module and where I was creating items programmatically. My basic understanding was If we have assigned workflow on standard value of any data template and creating items with C# code by using that data template then it should automatically inherits the workflow. But after creating items I found this is not the case and that Sitecore was not automatically applying the workflow.

So I started some digging, I found many post about create items in Sitecore programmatically, but didn’t find about create items programmatically with workflow. I found some posts where I got idea that how we can implement workflow on items.

Below is the API for creating Sitecore item programmatically with workflow assigned.

         Sitecore.Security.Accounts.User user = Sitecore.Security.Accounts.User.FromName(@"extranet\Anonymous", true);
            using (new UserSwitcher(user))

                Database master = Sitecore.Configuration.Factory.GetDatabase("master");
                TemplateItem template = master.GetTemplate("[Data Template ID]"); //TODO: Please enter your comment data template ID
                string workflowID = template.StandardValues[Sitecore.FieldIDs.DefaultWorkflow];
                Item parent = master.Items["Parent Item ID"]; //TODO: Please update parent item ID where you want to create items
                string validItemName = ItemUtil.ProposeValidItemName("Item Name").Trim();
                Item item = parent.Add(validItemName, template);
                    //TODO: Please update field name of comment template
                    item.Fields["Name"].Value = "Name";
                    if (!string.IsNullOrEmpty(workflowID))
                        item.Fields[Sitecore.FieldIDs.Workflow].Value = workflowID;
                        IWorkflow wf = master.WorkflowProvider.GetWorkflow(workflowID);

                catch (Exception ex)
                    Sitecore.Diagnostics.Log.Info("Error:Issue with create item " + ex.Message, this);



Add your comment




  • Smithg623 said:
    10/2/2016 8:12 PM

    You have brought up a very excellent details , regards for the post. kaebceebedkgbdgd