How to Avoid recursive trigger in salesforce ?

Avoiding recursive triggers in Salesforce is crucial to prevent infinite loops and excessive consumption of system resources. Here are several strategies to achieve this:


Use a Static Variable or Flag: Utilize a static Boolean variable or a static set to keep track of whether the trigger logic has already been executed. This prevents the trigger from re-executing when it's not necessary.

public class TriggerHandler {
    private static Boolean isFirstRun = true;

    public static void onBeforeInsert(List<MyObject__c> newList) {
        if (isFirstRun) {
            // Trigger logic
            isFirstRun = false;
        }
    }

}


Use a Handler Class: Implement a separate handler class to encapsulate trigger logic. This class can have static variables to manage recursion and can be called from the trigger.

public class TriggerHandler {
    private static Boolean isFirstRun = true;

    public static void handleBeforeInsert(List<MyObject__c> newList) {
        if (isFirstRun) {
            // Trigger logic
            isFirstRun = false;
        }
    }
}

trigger MyObjectTrigger on MyObject__c (before insert) {
    TriggerHandler.handleBeforeInsert(Trigger.new);
}

Use a Trigger Framework: Implement a trigger framework that provides built-in mechanisms to prevent recursion. Frameworks like the Trigger Handler Framework by Kevin O'Hara and the Trigger Framework by Andy Fawcett offer solutions for this.

Use a Helper Class: Create a helper class to manage recursion prevention and handle trigger logic. The helper class can maintain state information using static variables.

Disable Triggers Temporarily: Disable triggers temporarily using a custom setting or a custom metadata type. This allows you to prevent recursion during data migration or bulk operations.

Optimize Trigger Logic: Review and optimize trigger logic to minimize the chances of recursion. Avoid performing DML operations within loops and ensure that trigger logic is efficient.

Unit Test Recursive Scenarios: Write unit tests to cover recursive scenarios and verify that triggers behave as expected. This helps identify and address recursion issues during development.

By implementing one or more of these strategies, you can effectively prevent recursive triggers in Salesforce and ensure the stability and reliability of your application.

Comments

Popular posts from this blog

Introduction to Salesforce Agent Script: Build Predictable AI Agents

Anti-Patterns in Salesforce Agentforce: What to Avoid When Building AI Agents

MCP vs. Traditional APIs: Choosing the Right Integration Approach