Friday, July 24, 2015

Automatically Submit Multiple Records to Approval through Apex

Hi Friends,

Today I am sharing one code snippet with you to automatically submit multiple records to approval process through apex.

Firstly you need to setup the approval process on which object you want to submit the records for Approval.

Than through your Apex Controller or Trigger you could process the records and send that for Approval.

//Create a List of Approval.ProcessSubmitRequest
List requests = new List();

// Process your List on which you need to send the records for Approval, It could be direct list or you could process the list from you inner query or whatever list you want to process, In my example I have used the list of Opportunity from a trigger:

for(Opportunity opp: Trigger.New){
// Create a instance of Approval.ProcessSubmitRequest to add that to the list initialized above
Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();

// Set the comment you want to add
req.setComments('Submitting request for approval');

// Set the object-id in the Approval.ProcessSubmitRequest instance
req.setObjectId(opp.Id);

//Add the instance to the list initialized above, before the for loop
requests.add(req);
}

// We need to capture the result of the approval, so initialize a list of Approval.ProcessResult
Approval.ProcessResult[] processResults = null;

// Apply Exception Handliing
try {
// The command Approval.process will submit all your record for Approval
processResults = Approval.process(requests);
}catch (System.DmlException e) {
System.debug('Exception Is ' + e.getMessage());
}

Point to Notice:
Sometimes our trigger doesn't submit our records for approval, so that time we need to check, whatever records we are submitting for Approval through our code, are they meeting the entry-level criteria successfully which we have defined in our approval process, so we have to apply the conditions and have to test it carefully.

You could ask me for any topic or any help if you need something specific, I will be happy to help you.

Thanks,

Amit Goyal

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.