Overview
Salesforce triggers (Apex triggers) run custom Apex code before or after record changes. Understanding the two primary trigger types — Before and After — is essential for designing robust, efficient, and governor-limit-friendly automation.
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. Use them when you need the record Id, or when you need to act on related records. 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
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 = prior to DB save; After = after DB save.
- Use for: Before = modify record fields, validation; After = work with related records, use record Id.
- DML: Avoid DML in before triggers for the same object; after triggers commonly perform DML on related objects.
- Access to Id: Before insert — Id is null; After insert — Id is available.
Best Practices
- Keep trigger logic thin — delegate business logic to handler classes.
- Use one trigger per object and implement a trigger framework or handler pattern.
- Bulkify all logic: always iterate over Trigger.new or Trigger.newMap and perform DML on collections.
- Avoid SOQL/DML inside loops — use maps and collections to minimize governor limit usage.
- Prefer using
before
when changing record fields; useafter
when you need the saved record Id or to modify related objects.
Summary
There are two main trigger types in Salesforce: Before and After. Before triggers modify and validate records prior to saving, while After triggers operate on saved records and related objects. Choosing the correct type keeps your org efficient and compliant with Salesforce governor limits.
Category: Interview Questions
Leave a Reply