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

Looking to Master Batch Apex Essential? Have a look at the course specially designed to Master Batch Apex.


Throughout the course, we'll delve into crucial subjects such as understanding Batch Apex's role, controlling batch size, harnessing the power of Database.Stateful, executing callouts, implementing best practices, exploring limitations, triggering batch classes from apex triggers, mastering future methods, and comprehending queueable Apex. Additionally, we'll discuss advanced concepts like chaining Batch Jobs and dissect real-world scenarios where Batch Apex proves invaluable.

Here's a glimpse of the comprehensive table of contents:

        1) What is Batch Apex in Salesforce?
        2) How to control number of batches in Batch Apex using scope size?
        3) What is Database.Stateful in Batch Apex in Salesforce?
        4) How to do callouts from Batch Apex in Salesforce?
        5) What are Salesforce batch apex best practices?
        6) What are Salesforce batch apex limitations?
        7) How to call batch apex class from apex trigger in Salesforce? 
        8) What is future method in Salesforce?
        9) What is Queueable apex in Salesforce?
      10) Explain chaining of Batch Jobs?
      11) Explain the error "Too many queueable jobs added to the queue"?
      12) Explain the error "Maximum stack depth has been reached"?
      13) Real time scenario for use of Batch Apex?
    

To further enhance your preparation, we've included a dedicated section with 30 interview questions, ensuring you're well-equipped to tackle any interview related to Batch Apex.

Get ready to embark on a learning journey that will sharpen your Batch Apex skills and open new doors of opportunity. Enroll now and let's delve into the world of Batch Apex together!

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