Surendra Sharma

Surendra Sharma

Search This Blog

Thursday, March 19, 2015

How to apply workflow to all the items of content tree in Sitecore

Its common scenario that, if you created items first and later on creating workflow then you have to manually apply those workflow on template’s standard values and content items.

If there are few items then it fine to do it  manually. But what if there are hundreds, thousands content item.

Best way is to apply them programmatically.

Here is a code to do it. Just put Home item ID or start item

var FirstItem = Sitecore.Context.Database.GetItem(new ID("{A00A11B6-E6DB-45AB-8B54-636FEC3B5523}")) ;
PrintName(FirstItem , 1);

Rest of the item should be iterate by following recursive function and apply workflow on all the items except folder item.

private Item PrintName(Item mainItem, int icounter)
{
    string f = new string('-', icounter);
    TextBox1.Text += f + mainItem.DisplayName + System.Environment.NewLine;

    try
    {
        if (!mainItem.DisplayName.Equals("Homepage"))
        {
            //Put Workflow ID here
            var workflow = Factory.GetDatabase("master").WorkflowProvider.GetWorkflow("{7E9BC450-18EE-401E-892A-1CEF27BF8D9B}");
            workflow.Start(mainItem);
        }
    }
    catch (Exception)
    {
        TextBox1.Text += "Error " + mainItem.DisplayName + System.Environment.NewLine;
    }

    if (mainItem.HasChildren)
    {
        icounter++;
        foreach (var myInnerItem in mainItem.Children.ToList())
        {
            PrintName(myInnerItem, icounter);
        }
    }

    icounter--;
    return null;
}

Please leave your comments or share this code if it’s useful for you.

No comments:

Post a Comment