Newer Version Available

This content describes an older version of this product. View Latest

Apex Approval Processing Example

The following sample code initially submits a record for approval, then approves the request. This example requires an approval process to be set up for accounts.

1swfobject.registerObject("clippy.codeblock-0", "9");
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public class TestApproval {
18    void submitAndProcessApprovalRequest() {
19        // Insert an account
20        Account a = new Account(Name='Test',annualRevenue=100.0);
21        insert a;
22           
23        User user1 = [SELECT Id FROM User WHERE Alias='SomeStandardUser'];
24            
25        // Create an approval request for the account
26        Approval.ProcessSubmitRequest req1 = 
27            new Approval.ProcessSubmitRequest();
28        req1.setComments('Submitting request for approval.');
29        req1.setObjectId(a.id);
30        
31        // Submit on behalf of a specific submitter
32        req1.setSubmitterId(user1.Id); 
33        
34        // Submit the record to specific process and skip the criteria evaluation
35        req1.setProcessDefinitionNameOrId('PTO_Request_Process');
36        req1.setSkipEntryCriteria(true);
37        
38        // Submit the approval request for the account
39        Approval.ProcessResult result = Approval.process(req1);
40        
41        // Verify the result
42        System.assert(result.isSuccess());
43        
44        System.assertEquals(
45            'Pending', result.getInstanceStatus(), 
46            'Instance Status'+result.getInstanceStatus());
47        
48        // Approve the submitted request
49        // First, get the ID of the newly created item
50        List<Id> newWorkItemIds = result.getNewWorkitemIds();
51        
52        // Instantiate the new ProcessWorkitemRequest object and populate it
53        Approval.ProcessWorkitemRequest req2 = 
54            new Approval.ProcessWorkitemRequest();
55        req2.setComments('Approving request.');
56        req2.setAction('Approve');
57        req2.setNextApproverIds(new Id[] {UserInfo.getUserId()});
58        
59        // Use the ID from the newly created item to specify the item to be worked
60        req2.setWorkitemId(newWorkItemIds.get(0));
61        
62        // Submit the request for approval
63        Approval.ProcessResult result2 =  Approval.process(req2);
64        
65        // Verify the results
66        System.assert(result2.isSuccess(), 'Result Status:'+result2.isSuccess());
67        
68        System.assertEquals(
69            'Approved', result2.getInstanceStatus(), 
70            'Instance Status'+result2.getInstanceStatus());
71    }
72}
73