Overview
Salesforce triggers (Apex triggers) run custom Apex code before or after record changes. Picking between before and after comes down to two questions: can you change field values without a second DML call, and does the record Id exist yet.
1. Before triggers
Before triggers run before a record is saved to the database. Use them to validate or modify record values without an extra DML call. Common use-cases include:
- Setting or normalizing field values (e.g., auto-populate defaults)
- Performing validations that aren't possible with declarative validation rules
- Preventing DML by adding errors to records (
record.addError())
Example (before insert):
trigger AccountBeforeInsert on Account (before insert) { for (Account a : Trigger.new) { if (a.Name == null) { a.Name = 'Default Account'; } } }
2. After triggers
After triggers run after the record has been saved to the database. That is when you have the record Id and anything else the database generated, so work on related records belongs here. Typical use-cases include:
- Creating or updating related records (child records) via DML
- Calling external services or performing operations that require the record Id
- Working with values generated by the database (e.g., auto-number fields)
Example (after insert):
trigger AccountAfterInsert on Account (after insert) { List contacts = new List(); for (Account a : Trigger.new) { contacts.add(new Contact(LastName='Primary', AccountId=a.Id)); } if (!contacts.isEmpty()) insert contacts; }
Key differences (quick reference)
- Timing: before runs prior to the database save, after runs once the save is done.
- Use for: before modifies and validates record fields, after works with related records and needs the record Id.
- DML: avoid DML on the same object in a before trigger. After triggers commonly perform DML on related objects.
- Access to Id: on before insert the Id is null, on after insert it is available.
Best practices
- Keep trigger logic thin and delegate the business logic to handler classes.
- Use one trigger per object, with a trigger framework or handler pattern behind it.
- Bulkify all logic: always iterate over Trigger.new or Trigger.newMap and perform DML on collections.
- Avoid SOQL and DML inside loops. Use maps and collections to keep governor limit usage down.
- Prefer
beforefor changing fields on the triggering record, andafterwhen you need the saved Id or want to modify related objects.
Summary
Before triggers modify and validate records on the way into the database. After triggers operate on records that are already saved, and on everything hanging off them. In an interview, the record Id is the giveaway: logic that needs an Id or touches a child record belongs in an after trigger, and logic that only sets or checks a field on the record in front of it belongs in a before trigger.
Category: Interview Questions
Leave a Comment