Apex Approval Processing Example
The following sample code initially submits a record for approval, then approves the request. This example assumes that a pre-existing approval process on Account exists and is valid for the Account record created.
1public class TestApproval {
2 void submitAndProcessApprovalRequest() {
3 // Insert an account
4 Account a = new Account(Name='Test',annualRevenue=100.0);
5 insert a;
6
7 User user1 = [SELECT Id FROM User WHERE Alias='SomeStandardUser'];
8
9 // Create an approval request for the account
10 Approval.ProcessSubmitRequest req1 =
11 new Approval.ProcessSubmitRequest();
12 req1.setComments('Submitting request for approval.');
13 req1.setObjectId(a.id);
14
15 // Submit on behalf of a specific submitter
16 req1.setSubmitterId(user1.Id);
17
18 // Submit the record to the existing process named PTO_Request_Process
19 req1.setProcessDefinitionNameOrId('PTO_Request_Process');
20
21 // Skip the criteria evaluation for the specified process
22 req1.setSkipEntryCriteria(true);
23
24 // Submit the approval request for the account
25 Approval.ProcessResult result = Approval.process(req1);
26
27 // Verify the result
28 System.assert(result.isSuccess());
29
30 System.assertEquals(
31 'Pending', result.getInstanceStatus(),
32 'Instance Status'+result.getInstanceStatus());
33
34 // Approve the submitted request
35 // First, get the ID of the newly created item
36 List<Id> newWorkItemIds = result.getNewWorkitemIds();
37
38 // Instantiate the new ProcessWorkitemRequest object and populate it
39 Approval.ProcessWorkitemRequest req2 =
40 new Approval.ProcessWorkitemRequest();
41 req2.setComments('Approving request.');
42 req2.setAction('Approve');
43 req2.setNextApproverIds(new Id[] {UserInfo.getUserId()});
44
45 // Use the ID from the newly created item to specify the item to be worked
46 req2.setWorkitemId(newWorkItemIds.get(0));
47
48 // Submit the request for approval
49 Approval.ProcessResult result2 = Approval.process(req2);
50
51 // Verify the results
52 System.assert(result2.isSuccess(), 'Result Status:'+result2.isSuccess());
53
54 System.assertEquals(
55 'Approved', result2.getInstanceStatus(),
56 'Instance Status'+result2.getInstanceStatus());
57 }
58}