Sub topic 12
Apex triggers: when code is justified
This chapter assumes you know the Salesforce data model, can navigate Setup and the Object Manager, and have seen the governor limits introduced in the previous chapter. You can read simple Apex and SOQL (Salesforce Object Query Language), but you don't need to write much of it.
What an Apex trigger is
An Apex trigger is code that runs automatically before or after a record is inserted, updated, deleted, or undeleted. It is attached to one object. Like a record-triggered flow, it runs inside the save transaction. Unlike a flow, it is written and tested as code, deployed through a change set or source control, and subject to the same governor limits as any other Apex.
A trigger declares which object it watches and which events it responds to:
trigger AccountTrigger on Account (before insert, before update) {
for (Account acc : Trigger.new) {
if (acc.AnnualRevenue != null && acc.AnnualRevenue >= 1000000) {
acc.Rating = 'Hot';
}
}
}This trigger sets Rating on the records being saved. It uses no DML (Data Manipulation Language) statement, because changes made to Trigger.new in a before event are saved with the record. A before-save record-triggered flow can do exactly the same job declaratively. Under the clicks-before-code principle, this example is a poor reason to write a trigger. It is here to show the mechanics.
Trigger context variables
Salesforce gives every trigger a set of context variables that describe the current transaction.
| Variable | Meaning | Available in |
|---|---|---|
| `Trigger.new` | List of the new versions of the records | insert, update, undelete |
| `Trigger.old` | List of the old versions of the records | update, delete |
| `Trigger.newMap` | Map of Id to new record | after insert, update, undelete, and before update |
| `Trigger.oldMap` | Map of Id to old record | update, delete |
| `Trigger.isBefore`, `Trigger.isAfter` | Which phase is running | all |
| `Trigger.isInsert`, `Trigger.isUpdate`, `Trigger.isDelete`, `Trigger.isUndelete` | Which operation is running | all |
| `Trigger.size` | Number of records in this invocation | all |
You can only change Trigger.new records directly in a before event. In an after event the records are read-only, so to change related records you must use DML on those records.
Why bulk safety is not optional
A trigger does not receive one record. It receives up to 200 records per invocation, for example from a data load, an API call, or a list view mass update. Every trigger must therefore work on a whole list.
The classic failure is a query or DML statement inside a loop:
// Anti-pattern: do not do this
trigger OpportunityTrigger on Opportunity (after update) {
for (Opportunity opp : Trigger.new) {
Account a = [SELECT Id, Description FROM Account WHERE Id = :opp.AccountId];
a.Description = 'Updated';
update a;
}
}With 200 records, this runs 200 queries and 200 DML statements. A transaction is limited to 100 synchronous SOQL queries and 150 DML statements, so the transaction fails with a limit exception. The fix is to collect Ids first, query once, change records in memory, and run one DML statement:
trigger OpportunityTrigger on Opportunity (after update) {
Set<Id> accountIds = new Set<Id>();
for (Opportunity opp : Trigger.new) {
if (opp.AccountId != null) {
accountIds.add(opp.AccountId);
}
}
List<Account> accounts = [
SELECT Id, Description FROM Account WHERE Id IN :accountIds
];
for (Account a : accounts) {
a.Description = 'Updated';
}
update accounts;
}Flow runs under the same limits, and the platform bulkifies most flow elements for you. In Apex, bulk safety is entirely your job.
When code is justified
Choose a trigger when the requirement cannot be met cleanly by a validation rule, formula, flow, or approval process. Typical reasons:
- Complex logic. Nested conditions, recursion over hierarchies, or calculations that would need dozens of flow elements and become hard to read.
- High volume. Data loads of hundreds of thousands of records where flow overhead matters, or where you need fine control over queries and memory.
- Capabilities Flow lacks. Custom Apex classes shared with other code, complex string or collection handling, or callouts structured in ways Flow cannot express.
- Strict transactional control. Partial-success handling with
Database.insert(records, false)and per-record error handling withaddError(). - Reuse and testability. Logic that other Apex, such as REST services or batch jobs, must also call, and that you want covered by unit tests.
Preference for familiarity is not a reason. If an admin team maintains the org and the logic is simple, a flow is easier to hand over.
One trigger per object, with a handler class
When several triggers exist on one object, Salesforce does not guarantee the order in which they run. A common convention is therefore one trigger per object, containing no logic except delegation to a handler class:
trigger AccountTrigger on Account (before insert, before update, after update) {
AccountTriggerHandler handler = new AccountTriggerHandler();
if (Trigger.isBefore) {
handler.beforeSave(Trigger.new, Trigger.oldMap);
} else if (Trigger.isAfter && Trigger.isUpdate) {
handler.afterUpdate(Trigger.new, Trigger.oldMap);
}
}public with sharing class AccountTriggerHandler {
public void beforeSave(List<Account> newRecords, Map<Id, Account> oldMap) {
for (Account acc : newRecords) {
if (acc.AnnualRevenue != null && acc.AnnualRevenue >= 1000000) {
acc.Rating = 'Hot';
}
}
}
public void afterUpdate(List<Account> newRecords, Map<Id, Account> oldMap) {
// Related-record work goes here, using one query and one DML statement
}
}This keeps order explicit, lets you unit test the handler without firing the trigger, and gives you one place to look when debugging. Note that oldMap is null on insert, so check for that before reading from it.
Doing work only when a value changes
A before update trigger runs on every update, including ones that touch unrelated fields. Compare old and new values to avoid unnecessary work and to prevent loops:
for (Account acc : Trigger.new) {
Account oldAcc = Trigger.oldMap.get(acc.Id);
if (acc.AnnualRevenue != oldAcc.AnnualRevenue) {
// react only to a revenue change
}
}This check is valid only in update events. In an insert, Trigger.oldMap is null.
Moving slow work out of the transaction
Everything a trigger does counts against the user's save. Callouts to external systems are not allowed directly in a trigger's synchronous context, and heavy processing slows the save and risks limit errors. Asynchronous Apex, covered in the next chapter, runs the work in a separate transaction with its own limits. A Queueable class is the usual first choice:
public class RecalculateRatingJob implements Queueable {
private List<Id> accountIds;
public RecalculateRatingJob(List<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext context) {
List<Account> accounts = [SELECT Id, AnnualRevenue FROM Account WHERE Id IN :accountIds];
for (Account acc : accounts) {
acc.Rating = (acc.AnnualRevenue != null && acc.AnnualRevenue >= 1000000) ? 'Hot' : 'Warm';
}
update accounts;
}
}
// Enqueue from Apex, for example inside a trigger handler:
// System.enqueueJob(new RecalculateRatingJob(accountIdList));Pass Ids, not full records, so the job reads current data when it runs.
Common errors
- SOQL or DML inside a loop. Causes "Too many SOQL queries: 101" or "Too many DML statements: 151" when records arrive in bulk.
- Updating the same object in an after trigger. Saving records that fire the same trigger again can recurse. Use a before trigger to change the record itself, and guard against repeated runs.
- Assuming one record. Code such as
Trigger.new[0]works in a manual test and fails in a data load. - Several triggers on one object. Execution order is undefined, so results can differ between runs.
- Hardcoded Ids. Record Ids differ between sandbox and production. Query by name or use custom metadata.
- Insufficient tests. Production deployment requires at least 75% Apex code coverage across the org, but coverage alone doesn't prove correctness. Test bulk (200 records) and the negative path.
How triggers fit in the order of execution
Before triggers run before validation rules, so they can set values that rules then check. After triggers run after the record is saved to the database but before the transaction commits. Record-triggered flows, assignment rules, and workflow field updates also take turns in this sequence, and a field update in one step can re-run earlier steps. A later chapter covers the full order and the conflicts it produces.
Checklist before writing a trigger
- Can a validation rule, formula, roll-up summary field, or flow do it? If yes, use that.
- Is the trigger the only one on this object, with logic in a handler class?
- Does the code avoid queries and DML inside loops?
- Does it handle 200 records, nulls, and insert versus update?
- Should slow or callout work move to a Queueable job?
- Do unit tests cover bulk, success, and failure?
Exercise
A trigger on Contact contains Account a = [SELECT Id FROM Account WHERE Id = :Trigger.new[0].AccountId];. It works when a user saves one contact but fails during a data load of 200 contacts. Name two problems and describe the fix.
Show answer
The code reads only the first record (Trigger.new[0]), so the other 199 contacts are ignored. If the query were moved into a loop to cover them, it would hit the 100-query limit. Fix it by looping over Trigger.new to collect AccountIds into a Set<Id>, running one SOQL query with WHERE Id IN :accountIds, storing results in a map, and processing each contact from the map. Use a single DML statement for any updates.
Exercise
A requirement says: "When an opportunity is saved, set a custom field to a value derived from two other fields on the same record." Should you write a trigger? Explain.
Show answer
Usually not. Setting a field on the same record is a before-save record-triggered flow, or a formula field if the value never needs to be stored independently. A trigger is justified only if the logic is too complex for Flow, must be shared with other Apex, or has volume needs that Flow cannot meet.