+ Start a Discussion
G!R!G!R! 

Interview Question :Reg: Triggers Scenario 1.

Hi All,

 

How can you handle a circular trigger? will you please explain with sample code please.

 

scenario: Having Object A and Object B.

In Object A, Lets field be  Xyz................................................In Object B, having field ABC

I have written triggers in both objects so that,

If a event occurs in Object A, trigger fires and update a field or something else in Object B. Similarly If a event happens in Object B, ttrigger fires and update a field or something else in Object A-This is called Circluar trigger.

 

How can we controll this type of trigger.

 

Thanks

GIRI

 

 

chris.noechris.noe

The Apex documentation provides a good description of trigger recursion and how to prevent it:

 

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

 

You can also find other great posts on this topic by doing a Google search for "recursive trigger salesforce".

G!R!G!R!

Hi Chris,

 

Thnkas for your reply.

 

But there is difference between Recursive trigger and Circular trigger.

 

I have been encountered about both the recursive and circular triggers in Interview.

Recursive- event occurs in Object A, trigger fires and update happens in Object B, then again trigger fires in B and change happens in Object C...this is like serial trigger keeps on goes based on relationships.

 

Circular- between two objects

 

Correct me If I am Wrong

Maneesh Gupta 11Maneesh Gupta 11
Both can be handled using Static variables
Ashish SahaiAshish Sahai
Hi GIRI,

Hope this will work

Trigger for Object A:

trigger CircularTriggerA on ObjectA (after update) {
List<string> lst = new List<string>();
    if(trigger.isupdate){
        if(RecursionExampleHandler.isFirstTime){
            RecursionExampleHandler.isFirstTime=false;
            
    for(ObjectA obj:trigger.new){
        if(obj.Xyz!=null){
            lst.add(obj.id);
        }
    }
        }
    }
    List<ObjectB> objB  = new List<ObjectB>();
    if(lst.size()>0){
    for(ObjectB ob: [select id,ABC from ObjectB{
        
        ob.ABC='anyvalue';
        objB.add(ob);
        
    }
    }
    update objB;
   
}


Trigger for Object B:

trigger CircularTriggerB on ObjectB (after update) {
List<string> lst = new List<string>();
    if(trigger.isupdate){
       if(RecursionExampleHandler.isFirstTime){
        RecursionExampleHandler.isFirstTime=false;
            
    for(ObjectB obj:trigger.new){
        if(obj.ABC!=null){
            lst.add(obj.id);
        }
    }
        }
    }
    List<ObjectA> objA  = new List<ObjectA>();
    if(lst.size()>0){
    for(ObjectA ob: [select id,xyz from ObjectA{
        
        ob.xyz='anyvalue';
        objA.add(ob);
    }
    }
    update objA;
}

Recursion Handler class:

public class RecursionExampleHandler {
public static Boolean isFirstTime=True;
    public static Boolean isFirstTime1=false;
}
}