Saturday 18 July 2020

Episode 4-Conceptual Questions on Apex Triggers

In this blog we will have insights about the questions which are conceptual and often been asked in Interviews.
I would recommend you to go through by earlier blog on Trigger so that your concepts are clear for this blog.Read till the end to know the Bonus Tip.Before wasting time let's get started😄.


Q.1 Why Trigger.newMap cannot be used in Before Insert Trigger Event?

In Before Insert Event , the Trigger.newMap will always be null because before context records are not 
yet saved to the database hence the ids of these records are not generated yet resulting in the null values.
Therefore you cannot use Before Insert Event in Trigger.newMap.

Q.2  What is record is read only Trigger Exception?

The Exception  'mytrigger: execution of AfterInsert caused by: System.FinalException: Record is read-only'
occurs when  you try to update the list of records which are read only in Trigger execution.

For Example:

trigger TriggerException on Contact (after insert,after update) {
     for(contact con:trigger.new){
     con.lastname ='Test Contact';
  }  
 }

In this above  example we are trying to update contact records which are read only in after insert or update events resulting into an above error.

We can only update the records using Trigger.new  in case of before events.For Example:

trigger TriggerException on Contact (before insert, before update) {
    
    for(contact con:trigger.new){
        con.lastname ='Test Contact';
    }
}

Q.3 What is Recursive Triggers and How to Avoid it?

Recursion occurs in Triggers when your code gets executed multiple times  in the infinite loop resulting in hitting the Governor limits and results in an exception "Maximum Trigger Depth Exceeded" .

For Example : If you have a trigger that fires on update of Account Object  that updates Contact records and  have another Trigger that fires on update of Contact Object  which updates the Account records then this scenario will result in an infinite loop.(there can be multiple scenarios similar to this one which can result in a recursion in your code)

One of the method by which you can avoid recursion using Boolean Static Variable in the code.
For Example:
Set a boolean static variable to true by default. Now the trigger will run only if this variable is true and then set the value of the variable to false after the trigger run one time.Lets see the code once and understand better.

//Trigger Handler Class

   public class RecursionHandler {
    public static Boolean FirstTime=true;
    }

//Trigger Code

  trigger TriggerExample on Account (after update) {
 
    Set<Id> accid= new Set<Id>();
    List<Contact> updatedList= new List<Contact>();
    if(RecursionHandler.FirstTime){
        RecursionHandler.FirstTime=false;
        for(Account a:Trigger.new){
            accid.add(a.id);
        }
        List<Contact> conlist=[select lastname,id from Contact where accountid in :accid];
        for(Contact c:conlist){
            c.lastname='Test';
            updatedList.add(c);
        }
        if(updatedList.size()>0)
            update updatedList;
    }
}

This above trigger will not run second time .

Q.4. Can Trigger  make the Call to Apex Callout Method?

Yes we can make an apex callout using Trigger but only it has to be asynchronous callout because the trigger flow cannot wait for the response to be received by the callout to an external system.

This can be done by executing the method using  @future(callout=true) method . Future method make sure that it executes Asynchronously i.e no need to wait for the response. You may be wondering what does callout=true parameter does? .Future method can also have native calls so in order to allow future method to callout an external web service we use callout=true parameter.

Q.5 Can we Call the Batch Apex from the Trigger?

Yes, we can call the batch apex from the trigger in the same way as we call the batch apex using apex code.
 
Thanks for reading my blog.If you like it do comment and follow my blog for any future updates.Keep Reading and sharing your Knowledge.✌

BONUS TIP: I have shared the few questions to get an idea about Triggers Conceptual Questions.You can answer any question asked ,if your concepts about trigger are clear.
So Focus on Concepts and rest will follow in Place.





















2 comments:

If you have any doubts ,Please let me know.

Episode 13 : RollUp Summary Trigger for Lookup Relationship

 As we all know we can use roll-up summary field logic only for the master-detail relationship, but in case you have the business requiremen...