function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Ed055Ed055 

Recursive trigger issue

I have a trigger on contact which fires after insert and update. I have created a helper class where all my logic exist.  I have created a static set  at class level . I add values to this SET inside my onInsertAndUpdate  method so as not to process those records again. At the top of my method I check if this static variable is null and only then do additional logic in the onInsertAndUpdate  method. The issue I'm having is that there are multiple workflow rules that fire and update contact record which result in this trigger firing multiple times.  I checked the debug log and looks like the static variable == null is true every time this onInsertAndUpdate   is called again and hence it goes though rest of the logic.  Please help me understand what is going on. 

Thanks.
 
public without sharing class ContactTriggerHandler {

private boolean m_isExecuting = false;
    private integer BatchSize = 0;
     public static Set <String> EmailSet = null;
    public ET_ContactTriggerHandler (boolean isExecuting, integer size){
        m_isExecuting = isExecuting;
        BatchSize = size;
    }
    
   
    
    
    public void onInsertAndUpdate (Contact[] updatedContacts, Map<ID, Contact> OldMap) 
    {
                if(EmailSet==null){ 
                //do something
                
                    EmailSet.add(something); 
                }
    }

}

 
Best Answer chosen by Ed055
Amit Chaudhary 8Amit Chaudhary 8
PLease check below blog how to stop recusrive trigger
http://amitsalesforce.blogspot.in/2015/03/how-to-stop-recursive-trigger-in.html

Solution :-
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 the variable false.
 
public class ContactTriggerHandler
{
     public static Boolean isFirstTime = true;
}
 
trigger ContactTriggers on Contact (after update)
{
    Set<String> accIdSet = new Set<String>(); 
    if(ContactTriggerHandler.isFirstTime)
    {
        ContactTriggerHandler.isFirstTime = false;
         for(Contact conObj : Trigger.New)
  {
            if(conObj.name != 'Test') 
     {
                accIdSet.add(conObj.accountId);
            }
         }
   // any code here
    }
}

You can check below post for trigger framwork
http://amitsalesforce.blogspot.in/2015/06/trigger-best-practices-sample-trigger.html

Please let us know if this will help you

Thanks
Amit Chaudhary