how to stop recursive trigger by Apex in Salesforce

APEX

Many of time developer face recursive trigger issue, means same trigger call more then one time. So we need to follow below Apex Triggers concept:-

Best practice for triggers:

One trigger per object so you don’t have to think about the execution order as there is no control over which trigger would be executed first.

Logic-less Triggers – use Helper classes to handle logic.

Code coverage 100%

Handle recursion – To avoid the recursion on a trigger, make sure your trigger is getting executed only one time. You may encounter the error : ‘Maximum trigger depth exceeded’, if recursion is not handled well. You can use Static Boolean variable in apex class and check the variable in Apex Trigger IF it is true then execute your logic and make it false so that trigger can not execute Again.

public class checkRecursive {
     Public static Boolean firstcall=false;
}
Trigger feedback on contact (after update) {

if(!checkRecursive.firstcall) {
       checkRecursive.firstcall = true;
       Id conId;
       for(contact c:trigger.new){
           conId=c.Id;
       }
       Contact con=[select id, name from contact where id!=:conId limit 1];
       con.email=‘test@gmail.com’;
       Update con;
}}

link

Leave a Reply