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:
- Updating the record being inserted or updated
- Doing something based on a record you’re modifying
- Setting field values based on some criteria;
- Sending an apex email based on the record being inserted or updated.
- Updating/creating records that are not being updated or inserted
- Creating a contact on an account that’s being edited;
- Changing a lookup value on a related record from the parent being edited.