Before Trigger Vs After Trigger

Before you write a trigger for any requirement, you face problem about whether to write trigger on Before or After event.  How do you decide?

Requirement – On Contact creation wanted to make the field value ‘HasOptedOutOfEmail’ to be checked by default.

To take decision – it really depends what you are trying to do. We need to consider if it can happen/ can be done before data has saved to database(i.e. before trigger). So you can modify the record in Trigger.new without having to call separate Update. This is the best approach if you’re looking to modify data in the records within Trigger.new.

After trigger happen only after data has been written to database. Example you are trying to create a related record, you need the parent record Id created.

Before Trigger :-

  • Updating the records being inserted or updated.
  • Doing something based on a record you’re modifying.
  •  Examples:
    • Setting field values based on some criteria.
    • Sending an apex email based on the record being inserted or updated.

After Trigger :-

  • Updating/creating records that are not being updated or inserted.
  •  Examples:
    • Creating a contact on an account that’s being edited;
    • Changing a lookup value on a related record from the parent being edited.

Answer to above requirement –

 trigger ContactBeforeTrigger on Contact (before insert) {  
   for(Contact con:trigger.new) {  
     con.HasOptedOutOfEmail = true;  
   }  
 }  
 Trigger ContactAfterTrigger on Contact (after insert) {  
   List<Contact> conList = new List<Contact>();  
   for(Contact conInTrigger : trigger.new){  
     Contact c = new Contact(Id = conInTrigger.Id, HasOptedOutOfEmail = true);  
     conList.add(c);    
   }  
   update conList;  
 }  

You can achieve either of the way as above. But its better to follow the Before trigger then to do using After trigger. Decide which one to be better for you ?

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s