Skip to main content
2 of 2
Added for loop example
crmprogdev
  • 41k
  • 9
  • 58
  • 116

You first to need have a class that creates a public static boolean like below:

public with sharing class TriggerUtil{

   public static boolean reEntry = false;

}

This variable gets evaluated upon each entry into the trigger. You do that something like below:

trigger Create_Targeting_Allocation on Opportunity (after insert) { 

   If(!TriggerUtil.ReEntry){

      TriggerUtil.ReEntry = True;

      // Run trigger logic

   } // end if

} // end 

The next time the trigger fires in the same execution context, the value of ReEntry will be 'True', so the trigger won't execute and that stops the recursion.

Recognize that if you have more than 200 records, such as when you're doing batch data entry or when your trigger has a SOQL for loop in it like below that could return more than 200 records, it can handle more than 200 records and will continue to process them in batches of 200 records without exiting the trigger:

// trigger that fires on Account
For(Contact c:  
               [SELECT Id, Name, 
               FROM Contact
               WHERE Id IN (SELECT Contact WHERE Contact.AccountID
               IN :Trigger.new]){
               // do stuff to contact
}
crmprogdev
  • 41k
  • 9
  • 58
  • 116