Triggers: Before vs After
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.