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

Error:-- Maximum trigger depth exceeded

Hi All,
         I am bit confused  about this error. i have made all the  things while make this . Anybody help me out ?
trigger MatchTrigger on Match__c (after insert, after update, after delete, before delete)

     if (Trigger.isAfter && (Trigger.isInsert || Trigger.isDelete))
       System.debug('*** Started calculation matches: ' +;
        Set<Id> aDemandIdSet = new Set<Id>();
         Set<Id> aSupplyIdSet = new Set<Id>();
         //Find all the properties involved in changes matches.
        for (Match__c aMatch : Trigger.isInsert ? : Trigger.old)
            if (aMatch.Supply__c != null)
            if (aMatch.Demand__c != null)
     //Perform search for count of matches in two types: when Property is set as Property1__c in match object
        //and when it was set as EnquiringProperty__c.
        List<AggregateResult> aMatchCountResult = [SELECT COUNT_DISTINCT(Demand__c) counter, Supply__c FROM Match__c WHERE Supply__c IN :aSupplyIdSet GROUP BY Supply__c];
        List<AggregateResult> aMatchCountResult2 = [SELECT COUNT_DISTINCT(Supply__c) counter, Demand__c FROM Match__c WHERE Demand__c IN :aDemandIdSet GROUP BY Demand__c];
        Map<Id, Supply__c> anUpdateMap = new Map<Id, Supply__c>();
         Map<Id, Demand__c> anUpdateMap1 = new Map<Id, Demand__c>();
        //Calculate total count as sum of two values.
        for (AggregateResult anAgrRes : aMatchCountResult)
            Id anId = (Id) anAgrRes.get('Supply__c');
            if (anId!= null)
                System.debug('*** Result count for Id ' + anId + ': ' + anAgrRes.get('counter'));
                anUpdateMap.put(anId, new Supply__c(Id = anId, MatchedProperties__c = (Decimal)anAgrRes.get('counter')));
        for (AggregateResult anAgrRes : aMatchCountResult2)
            Id anId = (Id) anAgrRes.get('Demand__c');
            if (anId != null)
                System.debug('*** Result2 count for Id ' + anId + ': ' + anAgrRes.get('counter'));
                Demand__c aProp = anUpdateMap1.get(anId);
                if (aProp == null)
                    aProp = new Demand__c(Id = anId, MatchedProperties__c = 0);
                    anUpdateMap1.put(anId, aProp);
                aProp.MatchedProperties__c += (Decimal)anAgrRes.get('counter');
        //For all the rest propertis set count as 0.
        for (Id aPropId: aSupplyIdSet)
            if (!anUpdateMap.containsKey(aPropId))
                anUpdateMap.put(aPropId,  new Supply__c(Id = aPropId, MatchedProperties__c = 0));
        System.debug('*** Uptdate Matches count for Properties: ' + anUpdateMap.values());
        update anUpdateMap.values();
        Share a new match.
    if(Trigger.isInsert && Trigger.isAfter)
        // We only execute the trigger after a Match record has been inserted 
        // because we need the Id of the Match record to already exist.
        // Match_Share is the "Share" table that was created when the
        // Organization Wide Default sharing setting was set to "Private".
        // Allocate storage for a list of Match__Share records.
        List<Match__Share> matchShares  = new List<Match__Share>();
        // For each of the Match records being inserted, do the following:
        for (Match__c match :
            // Create a new Match__Share record to be inserted in to the Match_Share table.
            Match__Share matchBrokerShare = new Match__Share();
            //Populate the Match__Share record with the ID of the record to be shared.
            matchBrokerShare.ParentId = match.Id;
            // Then, set the ID of user or group being granted access. In this case,
            // we’re setting the Id of the Hiring Manager that was specified by 
            // the Recruiter in the Hiring_Manager__c lookup field on the Match record.  
            // (See Image 1 to review the Match object's schema.)
            matchBrokerShare.UserOrGroupId = match.Match_Property_Broker__c;
            // Specify that the Hiring Manager should have edit access for 
            // this particular Match record.
            matchBrokerShare.AccessLevel = 'edit';
            // Specify that the reason the Hiring Manager can edit the record is 
            // because he’s the Hiring Manager.
            // (Hiring_Manager_Access__c is the Apex Sharing Reason that we defined earlier.)
            matchBrokerShare.RowCause = Schema.Match__Share.RowCause.Suggested_Property_Broker__c;
            // Add the new Share record to the list of new Share records.
        // Insert all of the newly created Share records and capture save result 
        Database.SaveResult[] matchShareInsertResult = Database.insert(matchShares, false);
        for(Database.SaveResult aSaveRes: matchShareInsertResult)
                Database.Error[] anErrors = aSaveRes.getErrors();
                for (Database.Error anError: anErrors)
                    System.debug('*** Got an error on insert Deal sharing: ' + anError.getMessage());
        If we change match Interested_in_Dealing__c  status to true, a new deal will be created.
    if (Trigger.isUpdate && Trigger.isAfter)
        // A new record is created on Deal object like opportunity created between both the Property Record owners on one match
        // if they wish to work together. it is triggerd by field Interested in dealing when checked by either of the record owner.
        List<Deal__c> dealsList = new List<Deal__c>();
        for(Match__c aMatchObject:
            Match__c anOldMatch = Trigger.oldMap.get(aMatchObject.Id);
            //Check if match is set as interested and both properties are available.
            if (aMatchObject.Interested_in_Dealing__c == true
                      && anOldMatch.Interested_in_Dealing__c == false
                      && (aMatchObject.Status_Match__c == 'Available' || aMatchObject.Status_Match__c == 'Duplicate')
                      && (aMatchObject.Demand_Status_Match__c == 'Available' || aMatchObject.Demand_Status_Match__c == 'Duplicate'))
                //Create new deal for such properties and match object.
                Deal__c newOpportunity = new Deal__c(); 
                newOpportunity.Name = aMatchObject.Name + 'On' + aMatchObject.Id + '-' + aMatchObject.Supply__c;
                newOpportunity.Close_Date__c =;
                newOpportunity.Stage__c = 'Shortlisted'; 
                newOpportunity.Match__c = aMatchObject.Id;
                newOpportunity.Demand__c = aMatchObject.Demand__c;
                newOpportunity.Supply__c= aMatchObject.Supply__c;
                System.debug('*** Create new deal: ' + newOpportunity);
        insert dealsList;
        When we remove the match object, the related deal will be also deleted.
    if (Trigger.isBefore && Trigger.isDelete)
        List<Deal__c> aDeleteDeals = new List<Deal__c>();
        //Find all deals for the removed matches
        List<Deal__c> aFullList = [SELECT Id, Stage__c FROM Deal__c WHERE Match__c IN :Trigger.oldMap.keySet()];
        for (Deal__c aDeal: aFullList)
            if (aDeal.Stage__c != 'Deal Closed Won')
        System.debug('Remove deals: ' + aDeleteDeals);
        delete aDeleteDeals;

Mudasir WaniMudasir Wani
Hi Rony,

The issue is that your code is in recursion.
To avoid this you need to create a static variable and set it to false once your actual business is executed.
In entry criteria you should check the value for it as well.

Below are some useful blogs!/feedtype=SINGLE_QUESTION_DETAIL&id=90630000000gsX3AAI

Please mark this as solution if this solves your problem, So that if anyone has this issue this post can help

Please put some debug statements within the if conditions placed at the beginning of the trigger and check whether these statements are coming multiple times or not. If they are coming multiple times that means your trigger is going into recurssion. If so, resolve it by using static variable.

Also, check if there is any other trigger which is fired as result of DML operations done in this trigger. This may also cause an issue.
sandeep sankhlasandeep sankhla
Hi rony,

Please refer below link for recurssionhandler calss and example how to use..

P.S. If my answer helps you to solve your problem please mark it as best answer. It will help other to find best answer.

Salesforce Certified Developer