+ Start a Discussion
Harjeet Singh 28Harjeet Singh 28 

CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY:LeadTrigger: execution of AfterUpdate\ncaused by: System.DmlException: Update failed. First exception on row 0 with id first error: CANNOT_INSERT_UPDATE_ACTIVATE_ENTITY, LeadTrigger: maximum trigger depth exceeded\

Hi All,

Recently I encoutered the issue of maximum trigger depth exceeded. The thing is functionality is working fine in sandboxes but somehow it is showing errors in PROD.
My functionality is to assign leads on round robin basis and during bulk upload it shows the errors

Below is my trigger
trigger LeadTrigger on Lead (before insert,before update,after insert,after update) {    
    if(Trigger.isAfter){
        if(trigger.isInsert || trigger.isUpdate){
        RoundRobinImplementationHelper.roundRobinImplementation(Trigger.NewMap.keySet());
  }
 }
}

Below is my Apex class which assigns leads to users in round robin basis
public class RoundRobinImplementationHelper {
    public static void roundRobinImplementation(Set<Id> leadSet){
        System.debug('roundRobinImplementation ');
      List<Lead> leadList = [Select Id, OwnerId, Lead_Number__c FROM Lead Where Id IN : leadSet];
        List<User> userList = new List<User>();
        Set<Id> queueIdSet = new Set<Id>();
        Set<Id> userIdSet = new Set<Id>();
        Integer index, leadNumber, teamSize;
        
        For(Lead leadIterate : leadList){
            If(String.valueOf(leadIterate.ownerId).startsWith('00G')){
                queueIdSet.add(leadIterate.ownerId);
            }
        }
        If(queueIdSet==null || queueIdSet.size()==0)return;
        System.debug('queueIdSet '+queueIdSet);
        For(GroupMember gm : [Select Id, UserOrGroupId FROM GROUPMEMBER WHERE GroupId IN : queueIdSet]){
            userIdSet.add(gm.UserOrGroupId);
        }
        userList = [Select Id, Name,  Profile.Name From User Where Id In : userIdSet AND ISACTIVE = true];
        If(userList==null || userList.size()==0)return;
        
        For(Lead leadIterate : leadList){
                if(leadIterate.Lead_Number__c!=null){
                    leadNumber = Integer.valueOf(leadIterate.Lead_Number__c);
                    teamSize = userList.size();
                    index = Math.MOD(leadNumber ,teamSize);//+1;
                    system.debug('index '+index);
                    leadIterate.OwnerId = userList[index].id;
                    system.debug('leadIterate.OwnerId '+ leadIterate.OwnerId);
            }
        }
    If(leadList!=null && leadList.size()>0){
            update leadList;
        }
    }
}

What else I need to do here?How can I remove this error?

Any help will be greatly appreciated

Many thanks in advance​​​​​​​
Khan AnasKhan Anas (Salesforce Developers) 
Hi Harjeet,

Greetings to you!

"maximum trigger depth exceeded" exception in Salesforce occurs mainly due to recursion.

Kindly implement a static variable in a class to avoid recursion. 

Handler Class:
public Class CheckRecursive {
    
    private static boolean run = true;
    
    public static boolean runOnce() {
        if(run) {
            run=false;
            return true;
        }
        else {
            return run;
        }
    }
}

Trigger:
trigger LeadClone on Lead (after insert) {
    
    if(CheckRecursive.runOnce()) {
         // Logic 
        
    }
}

Please refer to the below links which might help you further with the above issue.

http://www.infallibletechie.com/2014/05/how-to-avoid-recursive-trigger-in.html

https://salesforcescool.blogspot.com/2018/11/avoid-maximum-trigger-depth-exceeded.html

I hope it helps you.

Kindly let me know if it helps you and close your query by marking it as solved so that it can help others in the future. It will help to keep this community clean.

Thanks and Regards,
Khan Anas
Harjeet Singh 28Harjeet Singh 28
Hi @Anas-Thanks for ur response. Yes I am aware regarding the recursion of trigger and I did read lots of fine blogs on same over Internet. It would be great if you kindly help me to understand below pointer:
1.I already hv Apex class as shown in my question, Can't I simply create a static variable just after class definition and before round robin method definition (in between of class declaration and method definition) 
Static boolean leadRecusrion;
Static{
leadRecursion=true;
​​​​​​} 

2.What is the correct place to check the boolean variable inside trigger. Is it inside the After insert and after update declaration or Can we hv a check on boolean variables outside the is After Insert or Update context, I mean just after the lead trigger name definition 

If you can help me to get the answer for my questions above I will be good to go and will clear my doubts

Many thanks in advance