I have situation where I have a lot items in the Workbox
that I need to clear out.
I need to process these items so that they can be assigned a workflow state (without triggering workflow actions) according to this rule:
If the item has a state of draft or waiting for approval and there is a published version higher than the current version then set the workflow state to be x
worflowstate.
I haven't done much experimenting with workflow, so does anybody have any code samples or thoughts of how I could achieve this?
Here is a blog post about Changing workflow state of Sitecore items programmatically .
First you need to find all items in chosen workflow states:
IWorkflow[] workflows = Sitecore.Context.Database.WorkflowProvider.GetWorkflows();
IWorkflow chosenWorkflow = workflows[..]; // choose your worfklow
WorkflowState[] workflowStates = chosenWorkflow.GetStates();
foreach (WorkflowState state in workflowStates)
{
if (!state.FinalState)
{
DataUri[] itemDataUris = chosenWorkflow.GetItems(state.StateID);
foreach (DataUri uri in itemDataUris)
{
Item item = Sitecore.Context.Database.GetItem(uri);
/* check other conditions - newer version exists etc */
ChangeWorkflowState(item, newWorkflowStateId);
}
}
}
The simplest code for changing workflow state of Sitecore item without executing any actions related to the new workflow state is:
public static WorkflowResult ChangeWorkflowState(Item item, ID workflowStateId)
{
using (new EditContext(item))
{
item[FieldIDs.WorkflowState] = workflowStateId.ToString();
}
return new WorkflowResult(true, "OK", workflowStateId);
}
public static WorkflowResult ChangeWorkflowState(Item item, string workflowStateName)
{
IWorkflow workflow = item.Database.WorkflowProvider.GetWorkflow(item);
if (workflow == null)
{
return new WorkflowResult(false, "No workflow assigned to item");
}
WorkflowState newState = workflow.GetStates()
.FirstOrDefault(state => state.DisplayName == workflowStateName);
if (newState == null)
{
return new WorkflowResult(false, "Cannot find workflow state " + workflowStateName);
}
return ChangeWorkflowState(item, ID.Parse(newState.StateID));
}