Automating Approval process with Apex trigger

Lets take a sample requirement 'I want to submit an Opportunity record to Salesforce approval process when opportunity Amount is greater than one lakh'. Before writing the Trigger you first you should create a 'Salesforce Approval Process' and the process should have matching criteria(Greater than 1 lakh). To create a approval process go through this link.

My trigger is simple when you create an opportunity code will get fired and the record will be submitted to approval. If there is any error like 'Approval process is not defined' then it will be displayed on the page.

Trigger Code:

trigger OppSubmitForApproval on Opportunity (after insert) {

    for (Opportunity  oppFvar : Trigger.new) {

        if (oppFvar.Amount>100000) {

            // create new approval request 
            Approval.ProcessSubmitRequest req = new Approval.ProcessSubmitRequest();
            req.setComments('Submitted for approval. Please approve.');
            req.setObjectId(oppFvar.id);
            // submit the approval request
            Approval.ProcessResult result = Approval.process(req,false);
            
            //Display an error message if approval process fails
            Database.Error[] error=result.getErrors();
            for(Database.Error err : error) 
            {
                 oppFvar.adderror('Record not submitted');                            
            }
        }

    }

}

Here is the test class to cover the above trigger code.

@isTest
private class TestOppSubmitForApproval {

    static testMethod void testApprovalSuccess() {
        //creating new instance
        Opportunity opp = new Opportunity(Name = 'Forcewizard',
                                          Amount = 200000,
                                          CloseDate = Date.today(),
                                          Probability = 10,
                                          StageName = 'Prospecting');
       //inserting opportunity
       insert opp;
       
       //Querying the process item and validating.
       List<ProcessInstance> processInstances = [select Id, Status from ProcessInstance where TargetObjectId = :opp.id];
       System.assertEquals(processInstances.size(),1);

    }

}

Both the trigger code and test code is not bulkified make sure you bulkified your code. To bulkify the code go through this link.

I hope you find this article interesting, Rate this article if its useful to you.

Let me know your suggestions in comment section.

Rating: 
No votes yet