Showing posts with label trigger. Show all posts
Showing posts with label trigger. Show all posts

Friday, 22 November 2013

Run Once logic for avoiding multiple or recursive calling of trigger in Salesforce


             
Hi guys,
This is my first blog, so please correct my if I am wrong somewhere,
Here the simple but tricky question asked in many interviews of salesforce because it’s a common scenario comes many times that’s why I’m writing this,

Suppose you have to update a record in a trigger with after update event then what happens???

Here example:
trigger updateAccount on Account (after update) {
     List<Account> accList = new List<Account>();
     for (Account a : Trigger.new) {
        // some logic……
        //…………………………….
          accList.add(a);
     }
     update acclist;
}

If you execute the above code then, the trigger is recursively called and thoughts exception
CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, updateAccount: maximum trigger depth exceeded 

Because you trying to do updation in trigger which is also updating same record so it called itself again and again and again upto its limit,

Here the solution of this problem,
1         1.  Make a public class.
2      2.    In that class take a static Boolean variable.
3      3Then create a static method, which has if statement which returns true first time only.

 Code:

-->> A class with static boolean variable and method:-


public class runOnce{
    public static Boolean firstRun = false;   
    public static Boolean run(){
        if(!firstRun){
            firstRun = true;
            return firstRun;
        }
        return false;
    }
}

-->> Now change in trigger,

trigger updateAccount on Account (after insert, after update) {   
     if(runOnce.run()){
         List<Account> accList = new List<Account>();
         for (Account a : [Select ID from Account where Id in :Trigger.new]) {
        // some logic……
        //…………………………….
              accList.add(a);
         }
         update acclist;
     }
}

Hope it helps, Happy Coding...:)

Anurag Jain