Recursive Trigger in salesforce

How to avoid Recursive Trigger In Salesforce

APEX

What Is Recursion?

Below use case is main reason of Recursion:-

1. When my Account owner is changed, all Opportunities related to that Account should have the same Owner.
2. When my Opportunity owner is changed, the Account with which the Opportunity is related should have the same Owner.

How to Fix it

We need to create a separate class with static variables

AvoidRecursive.cls

public class AvoidRecursive {
	public static boolean isStartAccount = false;
	public static boolean isStartOpportunity = false;
}

To fulfill this first requirement, I need to create a trigger on Account object and change the related Opportunities Owner from Account Owner.

AccountOwnerChange

Trigger AccountOwnerChange on Account(After update){
  Set<Id> accIds = new Set<Id>();
	  for(Account acc : Trigger.New){
	    if(acc.OwnerId != acc.oldMap.get(acc.Id).OwnerId){
			 accIds.add(acc);

	    }
	}
}

if(accIds.size() > 0 ){
  Map<Id, Opportunity>  mapOpp = Map<Id,Opportunity>([Select Id,OwnerId, Name from Opportunity where Id IN: accIds]);
	for(Account acc : Trigger.New){
	  for(Opportunity opp : mapOpp.values()){
		opp.OwnerId = acc.OwnerId;
	  }
	}
	if(!avoidRecursive.isStartOpportunity){
		avoidRecursive.isStartAccount = true;

			update mapOpp.values();
		}
 }
  
} 

To fulfill this Second requirement, I need to create a trigger on Opportunity object and change the related Account Owner from Opportunity Owner.

OpportunityOwnerChange

Trigger OpportunityOwnerChange on Opportunity(After update){
  Map<Id,String> oppMap = new Map<Id,String>();
	  for(Opportunity opp : Trigger.New){
	  if(opp.OwnerId ! = trigger.oldMap.get(opp.Id).OwnerId){
		oppMap.put(opp.Id , opp);
	  }
	}
	
	Map<Id, Account> mapAccount = new Map<Id, Account> ([Select Id, OwnerId,OpportunityId from Account where OpportunityId IN: oppMap.keySet()]);
	
	for(Opportunity opp : oppMap.values()){
	    mapAccount.get(OpportunityId).OwnerId = opp.OwnerId;
	
	}
if(!avoidRecursive.isStartAccount){
     avoidRecursive.isStartOpportunity= true;
	
	update mapAccount.values();
}
	
	
}

uniquesymbol

Leave a Reply