Monday 23 May 2011

Writing Apex Trigger : Issues and Solutions ( Entry Criteria)

Hi All,

Here are some issues that we face using triggers

1) Triggers Gets executed every time when the sObject gets inserted or updated , even though we don't want so and want our trigger gets executed only when any condition as per our requirement gets satisfied.
Solution : The condition of your requirement is the entry criteria for your trigger and that entry criteria should checked before executing any logic in the trigger.
Ex : We need to copy account fax field to fax field of contact records for that account when account gets updated
   
trigger TriggerWithoutEntryCriteria on Account (after update) 
    {
        
        for(Account acc : Trigger.New)
            {   
                //Trigger Action Logic
                List<Contact> listCon = [Select Fax from Contact where AccountId =: acc.id];      
                for(Contact con : listCon)
                    {
                        con.Fax = acc.Fax;
                    }
                update listCon;    
           
            }
    }

Now this trigger does not have entry criteria and will execute every time when account record gets updated regardless the fax field is updated or not. Now we will add entry criteria to this trigger.
trigger TriggerWithEntryCriteria on Account (after update) 
    {
        Integer index = 0;       
        for(Account acc : Trigger.New)
            {
                //Check entry criteria
                if(acc.Fax != Trigger.Old[index].Fax)                
                    {
                         //Trigger Action Logic
                         List<Contact> listCon = [Select Fax from Contact where AccountId =: acc.id];      
                         for(Contact con : listCon)
                             {
                                 con.Fax = acc.Fax;
                             }
                         update listCon;    
                    }
                index++;
            }
    }
After adding the entry criteria we have made our Trigger Action Logic to execute only when Fax field of account is updated.
In above example SOQL and DML are used in for loop that should also be removed using collections as discussed in earlier posts.

Regards

1 comment:

  1. very beautiful explanation has been put up here for avoiding deadlock between two S-object which are inter related to invoke trigger on each other.

    ReplyDelete

Tweet