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;

}}