Share Your Experience With Others

Before Vs After Trigger

Before Trigger:

  • 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.
  • In case of update or validate record values before they’re saved to the database in the same object.
  • 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.
  • Fields like id,formula fields won’t be available in before insert triggers as well.

After Trigger:

  • Insert/Update related object, not the same object.
  • Notification Email.
  • used to access field values that are set by the system (such as a record’s Id or LastModifiedDate field)

Here you can see a simple example to differentiate the values we get in before and after insert trigger.

Trigger:

trigger.PNG

Trigger Handler:

triggerhandler.PNG

After inserting two Accounts from Anonymous Window, Following values i m getting.

before vs after.PNG

  • Here you can see id field is null is before insert.
  • Trigger.new is returning a list of Account records.
  • Trigger.NewMap is returning a Map<id,Account>.
  • Note : The records that fire the after trigger are read-only.
  • So if it is a before insert trigger, you can’t query those records. Some thing like:
  • List<Account> accList = [Select Id, Name From Account Where Id in :Trigger.New];
  • won’t work in before insert trigger because the records are not there yet. But it will work in before update trigger.

One response to “Before Vs After Trigger”

  1. Interview Preparation : Triggers : Interview Questions – SFDCWallah Avatar
    Interview Preparation : Triggers : Interview Questions – SFDCWallah

    […] Asynchronous Triggers Before Vs After Trigger […]

    Like

Leave a reply to Interview Preparation : Triggers : Interview Questions – SFDCWallah Cancel reply