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
SFDC Noob 1SFDC Noob 1 

maximum trigger depth exceeded Lead trigger event

I have a previous trigger in my org that i am trying to add another part to.
Here is my trigger to change lead owner based on a lookupfield and i am trying to add it to the longer trigger pasted after. But i am getting maxium trigger depth exceeded error when i try to add it. 
 
IF (trigger.isAfter){
         list<Lead> LeadList = [select id,channel_sales_manager__c,ownerid from Lead where id in: trigger.newmap.keyset()]; 
          for(Lead ld : LeadList){
              if(ld.channel_sales_manager__c != null){
                  ld.ownerid = ld.channel_sales_manager__c;
              }
              IF(ld.channel_sales_manager__c == null){
                  Group csmqueue = [SELECT Id FROM Group WHERE Name = 'Channel Sales Managers' AND Type = 'Queue' LIMIT 1];
                  ld.ownerid = csmqueue.Id;
              }
          }
          update LeadList ;
}

trigger PartnerPortalTrigger on Lead (before insert, after insert, after update) {

    if(Trigger.isInsert && Trigger.isBefore) {
        
      Id queueId = [SELECT Id FROM Group WHERE Name = 'Channel Sales Managers' AND Type = 'Queue' LIMIT 1].id;
      Id currentProfileId = userinfo.getProfileId();
      List<Profile> profileName = [SELECT Name FROM Profile WHERE ID = :currentProfileId LIMIT 1];
    
      for(Integer i = 0; i < Trigger.New.size(); i++){
          if(profileName[0].Name == 'Partner Portal User' || profileName[0].Name == 'Partner Manager' ||
            profileName[0].Name == 'Partner Community User') {
              Trigger.new[i].OwnerId = queueId;
              Trigger.new[i].Status = 'Channel Submitted';
          }
      }
    }
    if(Trigger.isInsert && Trigger.isAfter) {
        
        List<LeadShare> sharesToInsert = new List<LeadShare>();

        Id currentProfileId = userinfo.getProfileId();
        List<Profile> profileName = [SELECT Name FROM Profile WHERE ID = :currentProfileId LIMIT 1];
        
        List<Lead> toUpdate = new List<Lead>();
        toUpdate = [SELECT Id, CreatedById, Partner__c FROM Lead WHERE Id IN :Trigger.New];
        List<Lead> newLeads = new List<Lead>();
        
        for(Integer i = 0; i < Trigger.New.size(); i++){
            
            if(profileName[0].Name == 'Partner Portal User' || profileName[0].Name == 'Partner Manager' ||
            profileName[0].Name == 'Partner Community User') {
                          
                LeadShare leadShare = new LeadShare();
                leadShare.LeadId = Trigger.new[i].Id;
                leadShare.UserOrGroupId = Trigger.new[i].CreatedById;
                leadShare.LeadAccessLevel = 'Read';
                sharesToInsert.add(leadShare);

            }
        }
        
        insert sharesToInsert;
        
        for(Lead l : toUpdate) {
            if(l.Partner__c == null) {
                l.Partner__c = l.CreatedById;
                newLeads.add(l);
            }    
        }
        update newLeads;
        
    }
    
    
    if(Trigger.isUpdate) {
        //When a lead status is updated to "Channel Registered," this will
        //update the status on the corresponding Campaign Member record
         
        List<Lead> updatedLeads = new List<Lead>();
        Map<Id, CampaignMember> members = new Map<Id, CampaignMember>([SELECT Id, LeadId, CampaignId FROM CampaignMember WHERE LeadId IN :Trigger.New]);        
        List<CampaignMember> membersToUpdate = new List<CampaignMember>();
        Map<Id, CampaignMember> leadIds = new Map<Id, CampaignMember>();

        List<String> companies = new List<String>();
        List<String> domains = new List<String>();
        String nameToMatch1;
        String nameToMatch2;
        List<Lead> sameCompanyLeads = new List<Lead>();
        List<Lead> newLeadsToUpdate = new List<Lead>();
            
        for(Lead thisLead : Trigger.New) {
            Lead oldLead = Trigger.oldMap.get(thisLead.Id);
            
            Boolean oldLeadIsRegistered = oldLead.Status.equals('Channel Registered');
            Boolean newLeadIsRegistered = thisLead.Status.equals('Channel Registered');
            
            if(!oldLeadIsRegistered && newLeadIsRegistered) {
                updatedLeads.add(thisLead);
                
                nameToMatch1 = thisLead.Company;
                
                if (nameToMatch1 != null) {
                    nameToMatch1 = nameToMatch1.remove(',');
                    nameToMatch1 = nameToMatch1.remove('.');
                    nameToMatch1 = nameToMatch1.remove('Inc');
                    nameToMatch1 = nameToMatch1.remove('LLC');
                    nameToMatch1 = nameToMatch1.remove('Credit Union');
                    nameToMatch1 = nameToMatch1.remove('Company');
                    nameToMatch1 = nameToMatch1.remove('/');
                    nameToMatch1 = nameToMatch1.remove('&');
                    nameToMatch1 = nameToMatch1.remove('\'');
                    nameToMatch1 = nameToMatch1.replaceAll('[\\s]', '%');
                    
                    if (!nameToMatch1.endsWith('%')) {
                        nameToMatch1 += '%';
                    }
                    
                }
    
                nameToMatch2 = nameToMatch1.remove('Corp');
                nameToMatch2 = nameToMatch2.remove('FCU');
                nameToMatch2 = nameToMatch2.remove('CU');
                
                companies.add(nameToMatch1);
                companies.add(nameToMatch2);
                
                if(thisLead.Email_Domain__c != 'yahoo.com' && thisLead.Email_Domain__c != 'gmail.com' && 
                    thisLead.Email_Domain__c != 'hotmail.com' && thisLead.Email_Domain__c != 'zoho.com' &&
                    thisLead.Email_Domain__c != 'outlook.com') {
                    domains.add(thisLead.Email_Domain__c);
                }
            }
        }
        
        //If we find another lead in the Channel Submitted status with the same email domain OR the same company, 
        //we update the status as Channel Registered
        sameCompanyLeads = [SELECT Id, Email_Domain__c, Company, Status FROM Lead WHERE Owner.Name = 'Channel Sales Managers' AND Status IN('Channel Submitted') AND Id NOT IN :updatedLeads AND (Email_Domain__c IN :domains OR Company IN :companies)];
    
         //AND (Email_Domain__c IN :domains OR Company IN :companies)
        for(Lead thisLead : sameCompanyLeads) {
            thisLead.Status = 'Channel Registered (Affiliated)';
            newLeadsToUpdate.add(thisLead);    
        }
        
        for(CampaignMember thisCM : members.values()) {
            CampaignMember thisMember = members.get(thisCM.Id);
            leadIds.put(thisCM.LeadId, thisMember);
        }
        
        for(Lead thisLead : updatedLeads) {
           if(leadIds.containsKey(thisLead.Id)) {
               CampaignMember thisMember = leadIds.get(thisLead.Id);
               thisMember.Status = 'Channel Registered';
               membersToUpdate.add(thisMember);
           }
        } 
        
        try {
            Database.update( membersToUpdate );
            Database.update( newLeadsToUpdate );
        } catch(DmlException e) {
            System.debug('The following exception has occurred: ' + e.getMessage());
        }
    }
}

 
Abhishek BansalAbhishek Bansal
Hi,

Since you are updating the same object(Lead) in after trigger so a recursive call is made which call your trigger again and again.
In order to solve this you have to use a static variable and control the execution of your trigger on the basis of that varibale so that your trigger code will run only once.

Please let me know if you need more help on this.

Thanks,
Abhishek Bansal.

 
ankur manocha 20ankur manocha 20
This looks like a Recursive Trigger issue. Usually when you have maximum trigger depth exception this means that a trigger is getting recursively fired. You can only have something recursively fire 16 times (Max Stack Depth).
SFDC Noob 1SFDC Noob 1
The bottom long trigger by itself works and i don't get any erros. I just want to know where to add in the smaller trigger i posted first, into the long trigger.