Maximum trigger depth exceeded
"Maximum trigger depth exceeded" is an error message in Salesforce that occurs when there's a recursive trigger execution that exceeds the platform's governor limit.
Let's consider a scenario with a Contact object with a custom field called Total_Contacts__c. This field represents the total number of contacts associated with an account. We aim to ensure that this field is always up-to-date whenever a new contact is created, updated, or deleted.
To achieve this, we implement triggers on the Contact object that update the Total_Contacts__c field on the related Account object. Unfortunately, due to a mistake in the trigger logic, the triggers recursively update contacts and accounts, causing an error.
Here's an example
trigger UpdateTotalContacts on Contact (after insert, after update, after delete) {if (Trigger.isAfter) {
if (Trigger.isInsert || Trigger.isUpdate) {
List<Account> accountsToUpdate = new List<Account>();
for (Contact con : Trigger.new) {
// Update related account's Total_Contacts__c field
Account acc = [SELECT Id, Total_Contacts__c FROM Account WHERE Id = :con.AccountId];
acc.Total_Contacts__c = [SELECT COUNT() FROM Contact WHERE AccountId = :con.AccountId];
accountsToUpdate.add(acc);
}
update accountsToUpdate;
} else if (Trigger.isDelete) {
List<Account> accountsToUpdate = new List<Account>();
for (Contact con : Trigger.old) {
// Update related account's Total_Contacts__c field
Account acc = [SELECT Id, Total_Contacts__c FROM Account WHERE Id = :con.AccountId];
acc.Total_Contacts__c = [SELECT COUNT() FROM Contact WHERE AccountId = :con.AccountId];
accountsToUpdate.add(acc);
}
update accountsToUpdate;
}
}
}
Comments
Post a Comment