How should I determine whether to use Before or After when writing a trigger?

The title pretty much says it all.

Answer

Depends on your usage. From my experience here’s the break down:

Before

  • I’m updating the record that’s being updated/inserted – or doing something based on the record being modified
  • Examples: Set value of a pick list based on criteria. Send apex e-mail based on the record updated/inserted

After

  • I’m updating or creating records that are NOT being updated/inserted
  • Examples: Create a task of an Opportunity that’s been edited, Change a look up value on a related record from the Opportunity being edited

The main thing to consider is that the Before happens before the data has been written to the server. This means you can modify the records in “Trigger.new” without having to call a separate “Update.” This is ideal if you want to modify data in the records within Trigger.new

After happens after the data has been written to the server. This is important when wanting to create additional related records (Can’t create a related record until AFTER the parent has been inserted).

I find about 95% of all the triggers I have ever written are Before Update/Insert. It’s very rare that I need a trigger that runs AFTER.

Attribution
Source : Link , Question Author : jackerman09 , Answer Author : Salesforce Wizard

Leave a Comment