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");public 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 specific process and skip the criteria evaluation
19        req1.setProcessDefinitionNameOrId('PTO_Request_Process');
20        req1.setSkipEntryCriteria(true);
21        
22        // Submit the approval request for the account
23        Approval.ProcessResult result = Approval.process(req1);
24        
25        // Verify the result
26        System.assert(result.isSuccess());
27        
28        System.assertEquals(
29            'Pending', result.getInstanceStatus(), 
30            'Instance Status'+result.getInstanceStatus());
31        
32        // Approve the submitted request
33        // First, get the ID of the newly created item
34        List<Id> newWorkItemIds = result.getNewWorkitemIds();
35        
36        // Instantiate the new ProcessWorkitemRequest object and populate it
37        Approval.ProcessWorkitemRequest req2 = 
38            new Approval.ProcessWorkitemRequest();
39        req2.setComments('Approving request.');
40        req2.setAction('Approve');
41        req2.setNextApproverIds(new Id[] {UserInfo.getUserId()});
42        
43        // Use the ID from the newly created item to specify the item to be worked
44        req2.setWorkitemId(newWorkItemIds.get(0));
45        
46        // Submit the request for approval
47        Approval.ProcessResult result2 =  Approval.process(req2);
48        
49        // Verify the results
50        System.assert(result2.isSuccess(), 'Result Status:'+result2.isSuccess());
51        
52        System.assertEquals(
53            'Approved', result2.getInstanceStatus(), 
54            'Instance Status'+result2.getInstanceStatus());
55    }
56}
57