Monday 27 June 2016

Sitecore default workflow not getting set when creating item programmatically


This was a weird issue which we faced today.  We were creating few sitecore items programmatically from an RSS feed. The Sitecore items were using press release template and we had assigned default workflow in standard values of the template.

But the programmatically created items  were not getting workflow and workflow state from default workflow set for that item. It was coming  empty. However it was working fine when we were creating an item manually. Lastly we had to set the workflow  programmatically using below code. This code will get the default workflow from item and set the workflow and workflow state.




           string defaultWorkFlowId = feedItem["__Default workflow"];
                    feedItem["__Workflow"] = defaultWorkFlowId;
                    feedItem["__Workflow state"] = GetDraftStateOfWorkflow(defaultWorkFlowId);
                 

Here is the function which is getting called

   private static string GetDraftStateOfWorkflow(string defaultWorkFlowItemId)
        {
            try
            {
                Sitecore.Data.ID workflowId = new ID(defaultWorkFlowItemId);
                Sitecore.Data.Database master = Sitecore.Data.Database.GetDatabase("master");
                if (!workflowId.IsNull)
                {
                    Item workFlowitem = master.GetItem(workflowId);
                    Item draftItem = workFlowitem.HasChildren?workFlowitem.Children.First(i => i.Name.ToLower() == "draft"):null;
                    if (draftItem != null)
                    {
                        return draftItem.ID.ToString();
                    }
                    else
                    {
                        return string.Empty;
                    }
                }
                else
                {
                    return string.Empty;
                }
            }
            catch(Exception)
            {
                return string.Empty;
            }
        }
   

Happy Automation :)

No comments:

Post a Comment