Approval Process(批准过程)简介

批准过程是一个复杂的业务过程。详细的内容可以参考官方文档。

英文版

中文版

官方trailhead模块

在Apex中调用Approval Process

在Apex中可以使用以下类对Approval Process进行操作:

  • ProcessInstance:可以用来查询或遍历Approval Process过程。
  • ProcessInstanceHistory:只读对象,不能直接被SOQL查询。代表了Approval Process过程的所有步骤和相关的状态为“pending”的请求。
  • ProcessInstanceStep:代表了Approval Process过程的一个步骤。
  • ProcessInstanceWorkitem:代表了Approval Process过程相关的状态为“pending”的请求。

在Apex中可以使用SOQL对ProcessInstance进行查询,而对于其他三个类的查询一般是作为对ProcessInstance查询的子语句来进行。

SELECT Id, (SELECT Id, StepStatus, Comments FROM Steps)
FROM ProcessInstance

上面这段代码可以查询Approval Process过程的Id,并查询其包括的步骤的各个属性。

SELECT Id, (SELECT Id, ActorId, ProcessInstanceId FROM Workitems)
FROM ProcessInstance

上面这段代码可以查询Approval Process相关的状态为“pending”的请求(Workitems)。

SELECT Id, (SELECT Id, StepStatus, Comments FROM StepsAndWorkitems)
FROM ProcessInstance

上面这段代码可以查询Approval Process过程的历史记录。

SELECT Id, ActorId, ProcessInstanceId
FROM ProcessInstanceWorkitem
WHERE ProcessInstanceId = 'XXXX'

上面这段代码可以查询和某个Approval Process的相关的所有状态为“pending”的请求。

官方代码示例

以下代码拷贝自官方文档,作为使用Approval Process的示例:

public class TestApproval {
void submitAndProcessApprovalRequest() {
// Insert an account
Account a = new Account(Name='Test',annualRevenue=100.0);
insert a; User user1 = [SELECT Id FROM User WHERE Alias='SomeStandardUser']; // Create an approval request for the account
Approval.ProcessSubmitRequest req1 =
new Approval.ProcessSubmitRequest();
req1.setComments('Submitting request for approval.');
req1.setObjectId(a.id); // Submit on behalf of a specific submitter
req1.setSubmitterId(user1.Id); // Submit the record to specific process and skip the criteria evaluation
req1.setProcessDefinitionNameOrId('PTO_Request_Process');
req1.setSkipEntryCriteria(true); // Submit the approval request for the account
Approval.ProcessResult result = Approval.process(req1); // Verify the result
System.assert(result.isSuccess()); System.assertEquals(
'Pending', result.getInstanceStatus(),
'Instance Status'+result.getInstanceStatus()); // Approve the submitted request
// First, get the ID of the newly created item
List<Id> newWorkItemIds = result.getNewWorkitemIds(); // Instantiate the new ProcessWorkitemRequest object and populate it
Approval.ProcessWorkitemRequest req2 =
new Approval.ProcessWorkitemRequest();
req2.setComments('Approving request.');
req2.setAction('Approve');
req2.setNextApproverIds(new Id[] {UserInfo.getUserId()}); // Use the ID from the newly created item to specify the item to be worked
req2.setWorkitemId(newWorkItemIds.get(0)); // Submit the request for approval
Approval.ProcessResult result2 = Approval.process(req2); // Verify the results
System.assert(result2.isSuccess(), 'Result Status:'+result2.isSuccess()); System.assertEquals(
'Approved', result2.getInstanceStatus(),
'Instance Status'+result2.getInstanceStatus());
}
}
04-19 18:40