Controlling Recursive Triggers

Sometimes we need to update the record of same object, which is intializing the trigger. This will cause recursive trigger and throws an exception. Exception could be "SELF_REFERENCE_FROM_TRIGGER"
For example, suppose you have self look up to contact named spouse. You have two contact, A and B. when you select A as spouse of B, you want to also update A as spouse of B. In trigger for A, when you update B, it will call recursive trigger.
To control/prevent such condition, we need to add a static variable in another class, as this variable will share single instance, as these transaction has occured from a single event. This static variable allows the code to execute in first run. but prevent from any run thereafter.



code for static var:


public class flag {
public static boolean firstrun = true;
}

code for trigger:


trigger MatchSpouse on Contact (after insert, before update) {
List spouses = new List();
Contact spouse;
for (Contact c : Trigger.new){
if (c.Spouse__c != null){
spouse = new contact(id = c.spouse__c);
if(spouse.Spouse__c != c.id)
{
spouse.Spouse__c = c.id;
spouses.add(spouse);
}}}
if(spouses.size()>0 && flag.firstrun ){
flag.firstrun = false;
update spouses;

}}

1 comment:

  1. How to avoid Recursive Trigger in Salesforce

    To resolve recursive trigger please follow the below steps,

    1. Create a class with the Boolean variable and set this as true to avoid Recursive trigger.
    public class RecursiveHandler
    {
    public static Boolean isNotRecursive = true;
    }

    2. Check the Boolean flag value before process your condition and set the flag value to false at the beginning of your process. Once if you set this false, the recursion will stop.
    trigger DuplicateRecordMaker on Account (after insert, after update)
    {
    List accounts = new List();

    if(RecursiveHandler.isNotRecursive)
    {
    RecursiveHandler.isNotRecursive = false;

    for(Account currentAccount : Trigger.New)
    {
    Account acc = new Account();
    acc.Name = currentAccount.Name;
    accounts.add(acc);
    }

    insert accounts;
    }
    }

    Hope the above coding will helpful to solve recursive trigger error.

    ReplyDelete