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        
6        insert a;
7        
8        // Create an approval request for the account
9        Approval.ProcessSubmitRequest req1 = 
10            new Approval.ProcessSubmitRequest();
11        req1.setComments('Submitting request for approval.');
12        req1.setObjectId(a.id);
13        
14        // Submit the approval request for the account
15        Approval.ProcessResult result = Approval.process(req1);
16        
17        // Verify the result
18        System.assert(result.isSuccess());
19        
20        System.assertEquals(
21            'Pending', result.getInstanceStatus(), 
22            'Instance Status'+result.getInstanceStatus());
23        
24        // Approve the submitted request
25        // First, get the ID of the newly created item
26        List<Id> newWorkItemIds = result.getNewWorkitemIds();
27        
28        // Instantiate the new ProcessWorkitemRequest object and populate it
29        Approval.ProcessWorkitemRequest req2 = 
30            new Approval.ProcessWorkitemRequest();
31        req2.setComments('Approving request.');
32        req2.setAction('Approve');
33        req2.setNextApproverIds(new Id[] {UserInfo.getUserId()});
34        
35        // Use the ID from the newly created item to specify the item to be worked
36        req2.setWorkitemId(newWorkItemIds.get(0));
37        
38        // Submit the request for approval
39        Approval.ProcessResult result2 =  Approval.process(req2);
40        
41        // Verify the results
42        System.assert(result2.isSuccess(), 'Result Status:'+result2.isSuccess());
43        
44        System.assertEquals(
45            'Approved', result2.getInstanceStatus(), 
46            'Instance Status'+result2.getInstanceStatus());
47    }
48}