Handle Recursion in Opportunity Stage Updates

This trigger updates the Opportunity Description based on its Stage while preventing recursive updates, ensuring data consistency without infinite loops.

Learn more about triggers here: YouTube playlist.

Solution:

public class preventRecursion { public
           static Boolean firstCall=false;
}
trigger OpportunityTrigger on Opportunity(after
                 update){ if(Trigger.isUpdate){ if(Trigger.isAfter){
                 if(!preventRecursion.firstCall){
                 preventRecursion.firstCall=true;
             OpportunityTriggerHandler.updateStage(Trigger.New,Trigger.oldMap);
                 }
        }
}
             public class OpportunityTriggerHandler{ public static void
             updateStageRecursion(List<Opportunity>
             oppList,Map<Id,Oppotunity>oldMap){
             List<Opportunity> oppToBeUpdated= new List<Opportunity>();
             for(Opportunity opp: oppList){ if(opp.StageName==’Closed
             Won’||opp.StageName==’Closed
                          Lost’){
                                          Opportunity o= new Opportunity(id=opp.Id);
                                                                        if(opp.StageName==’Closed Won’){
                                                                                o.Description=’Opportunity is Closed Won’;
                                                                        }else if(opp.StageName==’Closed Lost’){
                                                                                 o.Description=’Opportunity is Closed Lost’;
                                                             }
                                          oppToBeUpdated.add(o);
                                         }
                                   }
                           if(!oppToBeUpdated.isEmpty()){
                           update oppToBeUpdated;
                      }
        }
}

Want to Apply As Content Writer?

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Cart

Let's get you started!

Interested in writing Salesforce Content?

Fill in this form and we will get in touch with you :)