« Back to blog

Changing Workflow State in Sitecore

A few weeks ago, I needed to change the workflow state of items in Sitecore; this particular change was to happen to a few particular items while Sitecore was handling the item:saved event. I tried several solutions I located via Google, most of which were some variation of getting the Workflow of an item, and then calling Workflow.Execute() and passing it the command I wanted to execute, the item, and some other assorted bits of data.

None of them worked; in fact, I got consistent complaints that WorkflowProvider.GetWorkflow(item) was returning null.

After beating my head against the wall for long enough to add a second window to my workspace, I recalled that Sitecore stored the workflow and workflow state in each item as a part of the Workflow section that the Standard Template inherited. The "__Workflow state" field is just a reference type field that contains the Sitecore ID of the workflow state the item is in. So, changing the state is as simple as getting the ID of the desired Workflow state and doing something like this:

item.Editing.BeginEdit();
item.Fields[Sitecore.FieldIDs.WorkflowState].Value = DESIRED_WORKFLOW_STATE_ID;
item.Editing.EndEdit(); 

In that bit of code, Sitecore.FieldIDs.WorkflowState is the same thing as "__Workflow state", I just think it's a little cleaner to use the built-in Sitecore value instead.

You can also change the actual workflow like so:

item.Fields[Sitecore.FieldIDs.Workflow].Value = DESIRED_WORKFLOW_ID;

Now ... you know the drill. With great power, comes great responsibility. If you change the workflow or workflow state this way, you've completely bypassed the Sitecore way of doing things. But, if you need a quick way to change the state and you can't get things to work via the API, this just might be the ticket for you.