5

We have the list of items in the Sitecore tree and all the items will be in a workflow.
we are updating these items programmatically and based on some condition, we have to assign the state of the workflow.
We are looking for some Sitecore API so that we can invoke the workflow using c# .


we are assuming associated workflow state action will execute.

  • So the only thing you want to do is to set "Workflow" and "Workflow State" fields to some values? – Marek Musielak Nov 28 '17 at 11:45
  • Or do you want to move item from one state in workflow to another and execute all the actions? – Marek Musielak Nov 28 '17 at 11:46
  • Yes, we want to set workflow state and if any state has publishing command item will get published to the web . – Abhimanyu Singh Nov 28 '17 at 11:49
7

Here is code which changes workflow state and executes actions:

public static WorkflowResult ChangeStateAndExecuteActions(Item item, ID workflowStateId)
{
    using (new EditContext(item))
    {
        item[FieldIDs.WorkflowState] = workflowStateId.ToString();
    }

    Item stateItem = item.Database.GetItem(workflowStateId);

    if (stateItem.HasChildren)
    {
        WorkflowPipelineArgs workflowPipelineArgs = new WorkflowPipelineArgs(item, null, null);

        Pipeline pipeline = Pipeline.Start(stateItem, workflowPipelineArgs);
        if (pipeline != null)
        {
            WorkflowCounters.ActionsExecuted.IncrementBy(pipeline.Processors.Count);
        }
    }

    return new WorkflowResult(true, "OK", workflowStateId);
}

I wrote it 4 years ago but it should still work.

You can read more in my blog post here:

https://www.cognifide.com/our-blogs/sitecore/changing-workflow-state-of-sitecore-items-programmatically/

|improve this answer|||||
  • I am currently upgrading a solution from Sitecore 7.2 to Sitecore 9.1 that has code based on your example here. When I try to build it is failing on the line that says "WorkflowCounters.ActionsExecuted.IncrementBy...". The error is "The name WorkflowCounters does not exist in the current context". It doesn't seem to understand what WorkflowCounters is. Has that changed from 7.2 to 9.1? – Corey Burnett Apr 8 '19 at 15:42
  • It likely has. But it's related to updating Performance Counters and can be safely ignored unless you're extremely picky about these ;-) – Mark Cassidy Jul 15 '19 at 12:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.