+ Start a Discussion
vandana rajuvandana raju 

when to use after trigger

Hello friends
I have a scenario where when a account field is udpated corresponding contact field descriptions also gets updated.
pls see code as follows , its working.
 
public class Account_ContactDescription
{
      public void Update_ContactDescription(Set<ID> accountIDs)
   {
      List<Contact> contactsToUpdate=new List<Contact>();
      
      List<Contact> conaccountIDs=[select Id,FirstName,LastName from contact where accountID IN :accountIDs];
      
      if (conaccountIDs.size() > 0 && conaccountIDs != NULL)
      {
         for(Contact con:conaccountIDs)
         {
         contactsToUpdate.add(new Contact(ID=con.ID, Description=con.FirstName+' '+con.LastName));
            
         }
      }
      
      Database.Update(contactsToUpdate,false);
   }
}

trigger trg_updateContactDescripton on Account (before Update) 
{
  
  if (trigger.IsUpdate)
  {
    Account_ContactDescription obj = new Account_ContactDescription();
    obj.Update_ContactDescription(Trigger.NewMap.Keyset());
  }
}

If I use   after Update event also it works, then my question is what is the specific case scenario where a user is forced to use after trigger.
pls elaborate

thanks
vandana
Leo10Leo10
Hi Vandana
see below is the difference between before and after trigger.

BEFORE trigger
BEFORE triggers are usually used when validation needs to take place before accepting the change. They run before any change is made to the database.

BEFORE trigger
AFTER triggers are usually used when information needs to be updated in a separate table due to a change.
They run after changes have been made to the database (not necessarily committed).

also, you can refer this link
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_order_of_execution.htm

Thank you
vandana rajuvandana raju
Hi nabeel
I understand the order of execution.
My specific point is the above code works even when we use after update even so  does it impact performance, this is what I am asking.

Thanks
vandana
Leo10Leo10
When you save a record (insert/update) Salesforce fires a DML statement to its database, internally.

All the code written in the "before update" triggers, executes BEFORE that DML is committed to Salesforce Database. The code is written in after trigger executes AFTER the commit is made.

Hence if you are trying to update any value in the record, on which the trigger is fired, you need not write an update call, specifically. But you need to do it in after triggers.
example, if a before trigger is written on Account and you want to change a value of one of the fields it would be
for(Account acc: Trigger.new)
{
if(acc.value__c='Temp')
    acc.Value__c = 'New value';
}
but if you will write this on after update you can't update the same field because data is already committed to database so value will be read only.
After update trigger generally works when you want to update any other object. for example, if you want to create a new task on account insertion or update you can write logic for that.
vandana rajuvandana raju
Hi nabeel
with reference to amy above code can u validate my code or pls suggest any change if reqd.

vandana
Deepak Pandey 13Deepak Pandey 13
whenever you write trigger try to write it on before. The reason is
1-its take less DML operation.
2- if in future your client come to requirement to add some validation then you will trouble or your company. 
 
PRABHAKARAN CHOCKALINGAMPRABHAKARAN CHOCKALINGAM
Here are my two cents,
If a ID of the object referred in an Trigger event is required, go for after Trigger. Otherwise before trigger works fine as suggested.
As you code is for a update event, a before trigger is good.
In case if the trigger is to create a child object when a Parent Object is inserted, we need to go for a after trigger as the IDs are available only after the parent record is created.
rajat Maheshwari 6rajat Maheshwari 6

Hi Vandana,

I am suggesting you to use after context instead before, because You are taking reference of account id, which got updated.

 

According to salesforce documentation, In case of cross object reference, we should move with after trigger context.

Below is code snippet in simple and best practice, please follow : -

// Trigger Part
trigger trg_updateContactDescripton on Account (before insert,before update,after insert,after update)

 {
if (trigger.isAfter && trigger.IsUpdate)
  {
     set<id> set_AccountId = new set<Id>();

for(Account a : Trigger.new)
 {
    if(a.Field != Trigger.oldMap.get(a.id).Field)            // Check old and new value of field
         set_AccountId.add(a.id)
 }

        if(set_AccountId!=null && !set_AccountId.isEmpty())
         {
              Account_ContactDescription obj = new Account_ContactDescription();
                obj.Update_ContactDescription(set_AccountId);
         }
}
}

// Class Part

public class Account_ContactDescription
  {
     List<Contact> contactsToUpdate;
public void Update_ContactDescription(Set<ID> accountIDs)

  
 {
    if(accountIDs!=null && !accountIDs.isEmpty())
      {



for(Contact con : [select Id,FirstName,LastName from contact where accountID IN :accountIDs])
  {
     con.Description = con.FirstName+' '+con.LastName

if(contactsToUpdate==null)
       contactsToUpdate = new List<Contact>();

     contactsToUpdate.add(con);
}

if(contactsToUpdate!=null && !contactsToUpdate.isEmpty())
    update contactsToUpdate;

}

 

 

 

PRABHAKARAN CHOCKALINGAMPRABHAKARAN CHOCKALINGAM
Hi Rajat, 
As the trigger is only referring to the updated Account for which it has to update the associated contact, before trigger works good.
In case, if we are trying to create a Contact based on the insertion of Account, then we would need to go for a After context as a ID of the Account is required to create the contact.
Thanks.
rajat Maheshwari 6rajat Maheshwari 6

Hi Prabhakaran,

I think, Trigger in after context must be ideal for this requirement also, 

Before Trigger is ideal for validation purpose and fun with same object (Not Cross object reference). It's ohk It is working now.

After Trigger is ideal when we need to utilize the cross object reference, Here contact is taking reference from updated account id.

It's my opinion that After Trigger context will not harm anyway, Am I right ?

Thanks

PRABHAKARAN CHOCKALINGAMPRABHAKARAN CHOCKALINGAM
Hi Rajat,
As this trigger is to update the contact based on an update to the Account(Account.ID already exists), before trigger is perfect. In case, if an after trigger is used, then we need to call a DML statement(why to call a DML statement unnecessarliy when it can be done thorugh before trigger) explicitly to update the contact.
On the other hand, if the requirement is to create a contact after an account is created, then we would go for a after insert trigger. because in this case, account.ID is not availalable before insert and we would need this ID to create a contact referencing the account for which we are creating the contact.
trigger be used in case of cross object reference irrespective of the context.
Thanks.
rajat Maheshwari 6rajat Maheshwari 6

Hi Prabhakaran,

I am just clear my doubt, I have no any offense about the same :)

Just to let you know, basic difference : - In before, we are fetching all contacts whose account got update before commited to database

In After, We are fetching all contacts whose accounts got updated after commited to database, What is the role of dml calling here?

 

In before trigger, we are also utilizing database.update (dml operation) to update contact. same we are doing in after context.

Please let me correct If I am wrong, but again according to me, Trigger in after context is ideal . If anything wrong with that, then automatically salesforce prevent by executing error alert (Read-only exception)

Thanks