Wednesday, 15 August 2018

what is the Recursive trigger and how to handle it?

Trigger when called over and over then its called recursive trigger.Below error will be display
if not controlled.

error message : maximum trigger depth exceeded

ex : Recursive code

Trigger AccountTrigger on Account(before insert)
{
    insert new Account(Name='test');

}

How to stop it ?

In order to avoid the situation of the recursive call,make sure your trigger is getting executed only one time.To do so, you can create a class with a static Boolean variable with default value true.

In the trigger,before executing your code keep a check that the variable is true or not.once you check,make a variable false.

ex :

public class checkRecursive
{

  private static boolean run=true;

  public static boolean runOnce()
  {
     if(run){
         run=false;
        return true;
      }
      else
       {
         return run;
       }

  }

}

Trigger AccountTrigger on Account(before insert)
{

    if(checkRecursive.runonce())
      {
        insert new Account(Name='test');
      }

}

No comments:

Post a Comment