sitecore Workflow Executing workflow command to change the workflow state


Example

Thanks to this great post

If we want to mimic the Sitecore UI behavior and execute the command which will change the workflow state, we need to use WorkflowProvider to get an instance of the workflow assigned to the given item and call Execute method with a chosen command ID. This will fire all the actions which are defined under the command item node, change the state of the item and fire all the auto-actions defined below the new state item node:

public static WorkflowResult ExecuteCommand(Item item, string commandName, string comment)
{
    IWorkflow workflow = item.Database.WorkflowProvider.GetWorkflow(item);
 
    if (workflow == null)
    {
        return new WorkflowResult(false, "No workflow assigned to item");
    }
 
    WorkflowCommand command = workflow.GetCommands(item[FieldIDs.WorkflowState])
        .FirstOrDefault(c => c.DisplayName == commandName);
 
    if (command == null)
    {
        return new WorkflowResult(false, "Workflow command not found");
    }
 
    return workflow.Execute(command.CommandID, item, comment, false, new object[0]);
}