Technical Issue – User want all new records for an object to be submitted to an Approval Process, however you do not want to the rely on users to manually click the ‘Submit for Approval’ button after creating all the records.
Solution – Create and test necessary Approval Process go through Setup / App Setup / Create / Workflow & Approvals / Approval Processes, implement this simple Apex Trigger (the following example is for the Account object). You will also need to create the test method to ensure code coverage if your current production Apex Classes do not provide adequate coverage also. You can also the add try / catch statements to ensure that the exceptions are caught and handled properly.
Code:
trigger accountApprovalSubmit on Account (after insert) {
// trigger on Account object
for (Account a : trigger.new) {
// to extract all new values on Accounts
Approval.ProcessSubmitRequest app = new Approval.ProcessSubmitRequest();
app.setObjectId(a.id);
//Add the id of account
Approval.ProcessResult result = Approval.process(app);
//pass Approval request in to approval process result set.
}
}
Other Example:
if(Trigger.isAfter)
{
if(Criteria matched)
{
system.debug('condition passed');
Approval.ProcessSubmitRequest req1 = new Approval.ProcessSubmitRequest();
req1.setComments('Submitting request for approval.');
req1.setObjectId(Trigger.old[0].Id);
List<id> userId = new List<Id> {userInfo.getUserId()};
req1.setNextApproverIds(userId);
approval.ProcessResult result = Approval.process(req1);
}
Conclusion: Using above code user can insert records without any operation of Submit for Approval Button.
No comments:
Post a Comment