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
bentonbenton 

Cloning Trigger (maximum trigger depth exceeded)

I created a trigger to clone a custom object (service_order__c) if one of its fields called "recurring" is True. When I create/edit my custom object I get maximum trigger depth error. I can not figure out why I am getting that. Please help

 

Trigger:

trigger createRecurring on Service_Order__c(after update, after insert)
{  
    
    List<Service_Order__c> soInsert = new List<Service_Order__c>();
    for (Service_Order__c hr : [Select id,Recurring__c,Building__c, RecordTypeId from Service_Order__c where id in: Trigger.new])
    {
            if(hr.Recurring__c == True){
            Service_Order__c newSO = hr.clone(true);
            soInsert.add(newSO);      
            }
    }
    update soInsert;
}

Best Answer chosen by Admin (Salesforce Developers) 
Ritesh AswaneyRitesh Aswaney

Since you're updating the records that originally fired the trigger, it goes into a recurisve loop, trying to invoke itself.

So you need to use a static variable to break the recursion.

 

Create a class or use an existing class, where you declare a static variable


public with sharing class TriggerUtil{

 

public static boolean serviceOrderExecuting = false;

 

}

 

Trigger:

trigger createRecurring on Service_Order__c(after update, after insert)
{  
//check that the trigger is not already executing   

if (!TriggerUtil.serviceOrderExecuting){

TriggerUtil.serviceOrderExecuting = true;
    List<Service_Order__c> soInsert = new List<Service_Order__c>();
    for (Service_Order__c hr : [Select id,Recurring__c,Building__c, RecordTypeId from Service_Order__c where id in: Trigger.new])
    {
            if(hr.Recurring__c == True){
            Service_Order__c newSO = hr.clone(true);
            soInsert.add(newSO);      
            }
    }
    update soInsert;

}
}

 

http://www.salesforce.com/docs/developer/cookbook/Content/apex_controlling_recursive_triggers.htm