Triggers: Before vs After

Matt/ March 10, 2016/ Salesforce

When you’re writing a trigger, you face a decision about whether your trigger will execute Before or After.  How do you decide?

It really depends what you’re trying to do.  Your biggest consideration should be that Before happens before the data has been written to the server.  So you can modify the record in Trigger.new without having to call a separate Update.  This is the best option if you’re looking to modify data in the records within Trigger.new.

After, of course, happens after the data has been written to the server.  An example of when to use this would be if you are creating related records (because you cannot create a related record before the parent has been persisted to the database).

Most often, my triggers are Before the update or insert.  In my experience it’s pretty uncommon to require a trigger to run After.

To break this down further:

Before:

  • Updating the record 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:

  • 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.
Share this Post

About Matt

Matt is a seasoned Salesforce Developer / Architect, with implementations of Sales Cloud, Service Cloud, CPQ, Experience Cloud, and numerous innovative applications built upon the Force.com platform. He started coding in grade 8 and has won awards ranging from international scholarships to internal corporate leadership awards. He is 37x Certified on the platform, including Platform Developer II, B2B Solution Architect and B2C Solution Architect.