我不会使用 Dhanuka777 的答案,因为它没有利用 Sitecore 的工作流状态命令和它附带的有用功能,例如电子邮件生成。它还需要硬编码Guids。
以下代码的好处:
- 利用 Sitecore 的状态命令和它们具有的出色功能,例如生成电子邮件以提醒用户等
- 不要将状态和命令的指南存储在解决方案中
- 独立于 Sitecore 的上下文
- 抽象,因此可用于 Sitecore 中的所有工作流。
public bool UpdateWorkflow(WorkflowState newWorkflowState, Item item)
{
Assert.ArgumentNotNull(newWorkflowState, "The new WorkflowState can not be null");
Assert.ArgumentNotNull(item, "Item can not be null");
bool successful = false;
WorkflowState currentWorkflowState = GetWorkflowStateForItem(item);
if (currentWorkflowState != newWorkflowState)
{
IWorkflow workflow = GetWorkflowOfItem(item);
if (workflow != null)
{
List<WorkflowCommand> applicableWorkflowCommands = workflow.GetCommands(currentWorkflowState.StateID).ToList();
foreach (var applicableWorkflowCommand in applicableWorkflowCommands)
{
Item commandItem = _database.GetItem(applicableWorkflowCommand.CommandID);
string nextStateId = commandItem["Next state"];
if (nextStateId == newWorkflowState.StateID)
{
WorkflowResult workflowResult = workflow.Execute(applicableWorkflowCommand.CommandID, item, "", false);
successful = workflowResult.Succeeded;
break;
}
}
}
}
else
{
successful = true;
}
return successful;
}
public WorkflowState GetWorkflowStateForItem(Item item)
{
var workflow = GetWorkflowOfItem(item);
return workflow != null ? workflow.GetState(item) : null;
}
public IWorkflow GetWorkflowOfItem(Item item)
{
return _database.WorkflowProvider.GetWorkflow(item);
}
private Database _database
{
get
{
return Sitecore.Data.Database.GetDatabase("master");
}
}