Approval Process using Apex

How to Submit for Approval using Apex, which is equivalent to "Submit For Approval" Button

Account a = new Account(Name='Dummy Account',annualRevenue=5000.0);
insert a;

// Create an approval request for the account
Approval.ProcessSubmitRequest process = new 	 Approval.ProcessSubmitRequest();
process.setComments('Submitting request for approval.');
process.setObjectId(a.id);

Note: Some times even we submit like above the Record will not be submitted it may because of following reasons

  1. Criteria not met in Approval steps
  2. Record Id may be null

So before proceeding to above steps please ensure record is going to meet Criteria that set in Approval steps

How to Approve/Reject record using Apex, this comes after submitting record

List<Id> newWorkItemIds = result.getNewWorkitemIds();

// Instantiate the new ProcessWorkitemRequest object and populate it
Approval.ProcessWorkitemRequest req2 = new Approval.ProcessWorkitemRequest();
req2.setComments('Approving request.');
// you can Approve/Reject here
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);

If result2.isSuccess() is true then Record is successfully approved

Subscribe to Phanindra Mangipudi

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
jamie@example.com
Subscribe