fbpx

Free Salesforce Developers Tutorials >

Chapter - 9 Apex Triggers >

Handling Recursion In Triggers

Handling Recursion In Triggers

What You’ll Learn


S2 Labs

What Is Recursion In Triggers? 

Recursion in Triggers happens when a Trigger is called repeatedly, resulting in an infinite loop.

To counter recursion, we need to:

  1. Create another class called RecursiveTriggerHandler.
  2. Make use of “Static” variables.

Example:

trigger BranchTrigger on Branch__c(before update) {
            if (RecursiveTriggerHandler.isFirstRun) {
                RecursiveTriggerHandler.isFirstRun = false;
                // Call Helper Class method 
                BranchTriggerHelper.firstMethod(Trigger.new);
            }

The first instance of the Trigger is run and if this variable is true, the logic in the Helper Class executes.

Other Best Practices for writing triggers:

  1. Always create only one Trigger per object.
  2. Create logic-less Triggers and use Helper Class Design Pattern in which the helper class will contain all the logic.
  3. Create context-specific handler methods in the Helper Class.
  4. Bifurcate “insert” and “update” Trigger logic contexts and create two different methods in the Trigger’s helper class.

 trigger PositonTrigger on Position__c(after insert, after update) {
            if (Trigger.isAfter && Trigger.isInsert) {
                PositionTriggerHandler.handleAfterInsert(Trigger.new);
            } else if (Trigger.isAfter && Trigger.isUpdate) {
                PositionTriggerHandler.handleAfterUpdate(Trigger.new, Trigger.old);
            }
        }

Salesforce Developer

 

Download Study Material

Get access to exclusive study material for Salesforce Certification and ace your exams!

Download Now

Our Salesforce Certification Courses

Hey there! Glad you made it through our Salesforce Developer Training for beginners . But wait! We've got some high-in-demand Salesforce courses for you to take your Salesforce skills to the next level, making you a desired professional in the Salesforce job market.

Post a Comment

Your email address will not be published. Required fields are marked *