Monday, October 28, 2019

HOW TO CALL BATCH APEX CLASS FROM APEX TRIGGER IN SALESFORCE


Is it possible to call a batch apex from the trigger?

Yes it is possible, we can call a batch apex from trigger but we should always keep in mind that we should not call batch apex from trigger each time as this will exceeds the governor limit this is because of the reason that we can only have 5 apex jobs queued or executing at a time.

Now let’s see how we can call a batch apex from the trigger.

SCENARIO:  We are having the requirement that whenever a contact record is inserted we want a welcome email to be sent to contact email address and for this, we are asked to write a batch apex class which will be called from the trigger on “after insert “ event  on the contact record and will send emails to contact.

APEX TRIGGER:

trigger maintrigger on Contact (after insert) {
    Map<id,contact> IdContactMap=new Map<Id,contact>();
    for(Contact con:trigger.new){
        if(con.email!=Null){
            IdContactMap.put(con.id,con);
        }
    }
    if(IdContactMap.size() > 0){
        database.executeBatch(new MailToNewContact(IdContactMap)); // Calling batch class.
    }

}

BATCH APEX:

global class MailToNewContact implements Database.Batchable<sObject>
{
    Map<id,contact> IdContactMapBatch=new Map<id,contact>();
    global MailToNewContact(Map<id,contact> IdContactMap){
        IdContactMapBatch=IdContactMap;
    }
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
        return Database.getQueryLocator([SELECT id,firstname,email from contact where id in:IdContactMapBatch.keySet()]);
    }
    global void execute(Database.BatchableContext BC, List<Contact> scope) {     
        for(Contact con : scope)
        {    
           Messaging.SingleEmailMessage email=new Messaging.SingleEmailMessage();
               email.setToAddresses(new string[] {con.email});
               email.setSubject('Welcome Mail');
               email.setPlainTextBody('Welcome Your Contact Is Created Successfully In Salesforce');
           Messaging.sendEmail(new Messaging.SingleEmailMessage[] {email});
        }
    }
    global void finish(Database.BatchableContext BC)
    {
    }
}

Now, let's try to insert 2 contacts at a time using .csv file as shown in the below image.

HOW TO CALL BATCH APEX CLASS FROM APEX TRIGGER IN SALESFORCE

can we call scheduled apex from trigger

call batch class from trigger

5 comments:

  1. But how to write test class for this trigger?

    ReplyDelete
  2. If you insert new contacts in test class, both trigger and batch class will get executed

    ReplyDelete
  3. how to write a test class for this trigger?

    ReplyDelete
  4. IF DO UPSERT IN BATCH,tRIGGER IS CALLING TWO TIMES SO BATCH IS EXECUTING TWO TIMES WHAT IS THE SOLUTION

    ReplyDelete
  5. how to write a test class for this scenario?

    ReplyDelete