Sub topic 2
The Seven Trigger Events
This chapter assumes you can read basic Apex (variables, loops, List, Set, Map) and know what a record, a field and a record Id are. It also assumes you have run DML statements and SOQL queries and know that governor limits exist. It covers the events a trigger can subscribe to and how to choose between them. Later chapters cover the variables available inside each event.
What a trigger event is
A trigger is Apex code attached to one object. Salesforce runs it when a save operation reaches a certain point. That point is the trigger event. You list the events you want in parentheses after the object name:
trigger AccountEventLogger on Account (
before insert, before update, before delete,
after insert, after update, after delete, after undelete
) {
System.debug(Trigger.operationType + ' fired with ' + Trigger.size + ' record(s)');
}Each event combines a timing (before or after) with an operation (insert, update, delete, undelete). That gives eight possible pairings, but Salesforce supports seven. The pairing before undelete does not exist, so the trigger above lists every legal event.
The events at a glance
| Event | Runs | Typical DML that causes it | Records you receive |
|---|---|---|---|
| `before insert` | Before new records are written | `insert`, `upsert` (new record), API creates | `Trigger.new` (no Ids yet) |
| `before update` | Before changes are written | `update`, `upsert` (existing record) | `Trigger.new`, `Trigger.old` and both maps |
| `before delete` | Before records are removed | `delete`, `merge` (losing records) | `Trigger.old`, `Trigger.oldMap` |
| `after insert` | After new records are written | Same as `before insert` | `Trigger.new`, `Trigger.newMap` (with Ids) |
| `after update` | After changes are written | Same as `before update` | `Trigger.new`, `Trigger.old` and both maps |
| `after delete` | After records are removed | Same as `before delete` | `Trigger.old`, `Trigger.oldMap` |
| `after undelete` | After records are restored from the Recycle Bin | `undelete` | `Trigger.new`, `Trigger.newMap` |
The next chapters explain why those record collections differ. For now, notice the pattern. Inserts and undeletes give you new data, deletes give you old data, and updates give you both.
The record lifecycle
The diagram shows where each event sits as a record moves through its life.
The last arrow shows that purging the Recycle Bin is not an event. Salesforce does not run a trigger when records are permanently removed from the bin. The same goes for a record that ages out of it.
Choosing the right event
Pick the event from what the requirement needs, not from habit. Ask three questions.
- Do I need to change the triggering record itself? Use a
beforeevent. Field changes made toTrigger.newin abefore insertorbefore updatetrigger are saved with the record, and you need no DML statement. - Do I need the record Id, or do I need to create or update other records? Use an
afterevent. A new record has no Id duringbefore insert, so you cannot link child records to it yet. - Do I need to reject the save? Either timing works with
addError. Abeforeevent is usually better because Salesforce has not done the save work yet.
Here are common requirements mapped to events.
| Requirement | Event | Reason |
|---|---|---|
| Default a field on new records | `before insert` | Edit `Trigger.new` directly |
| Stamp a date when a field changes | `before update` | Compare old and new values, then edit the record |
| Create a follow-up Task for each new Account | `after insert` | You need the Account Id for `WhatId` |
| Stop deletion of important records | `before delete` | Reject before anything is removed |
| Recalculate a parent total when children change | `after insert`, `after update`, `after delete`, `after undelete` | The child's final state is saved, and a restored child counts again |
| Reapply logic to restored records | `after undelete` | The only event for restores |
The rollup row is a classic mistake source. If you subscribe only to after insert and after update, the parent total goes stale when a child is deleted or restored. Cover all four events, or you will see drift that is hard to trace.
How operations map to events
Not every DML statement maps to a single event.
upsertfires insert events for rows that do not match an existing record and update events for rows that do. Oneupsertcall can therefore fire both sets of events, each with its own subset of records.mergefires delete events for the losing records and update events for the winning (master) record. Merged-away records are deleted, so abefore deletetrigger that blocks deletion can also block a merge.- Cascade deletes fire the child object's delete triggers when a parent is deleted. Deleting an Account can run
before deleteandafter deleteon its Contacts and Opportunities, if those triggers exist. - Undelete restores records and their related children where the platform restores them. It fires
after undeleteon each affected object that has such a trigger. - Hard delete and purge do not fire undelete or delete triggers for the purge itself, as the diagram shows.
Batches of up to 200 records
An event does not fire once per record. When a transaction saves many records, Salesforce passes them to the trigger in chunks of up to 200. A data load of 1,000 Accounts runs your before insert logic five times, each with up to 200 records in Trigger.new. Even a single-record save arrives as a list of size 1.
For this reason every trigger body should loop over the collection. It should never assume a single record. Chunks in the same transaction share the same governor limits, so a query inside the loop would fail. A later chapter covers the bulk-safe patterns in detail.
Several events in one trigger
You can write one trigger for all the events you need, or several triggers on the same object. Salesforce does not guarantee the order in which multiple triggers on one object run for the same event. Prefer one trigger per object, and branch inside it by event.
The trigger below subscribes to three events and branches with the Trigger.isBefore and Trigger.isAfter flags. A later chapter covers these and the other context variables.
trigger ContactEvents on Contact (before insert, before update, after undelete) {
if (Trigger.isBefore) {
for (Contact c : Trigger.new) {
if (String.isBlank(c.Title)) {
c.Title = 'Unknown';
}
}
} else if (Trigger.isAfter && Trigger.isUndelete) {
System.debug(Trigger.new.size() + ' contact(s) restored');
}
}In the before branch the trigger edits Trigger.new. That is legal because the records have not been saved. In the after branch, Trigger.new is read-only, so the trigger only reads it.
Common errors
- Subscribing to the wrong timing. Setting
WhatId = a.Idin abefore inserttrigger fails becausea.Idisnullat that point. Move the logic toafter insert. - Using
Trigger.newin a delete trigger. It isnullfor delete events. UseTrigger.old. - Forgetting
after undelete. Logic that tracks existing records, such as counts, sums or sharing, silently breaks when records return from the Recycle Bin. - Writing
before undelete. This does not compile. Salesforce reports an error for the unsupported event. - Editing records in an
aftertrigger. Records inTrigger.neware read-only after the save. Salesforce throws aSystem.FinalExceptionif you assign to a field. Query or create separate record instances if you need to change data after the save. - Assuming one record per call. A trigger that reads only
Trigger.new[0]ignores up to 199 other records.
Exercise
A requirement says: "Whenever a Contact is deleted, restored, or created, update a count field on its parent Account." Which trigger events on Contact must you subscribe to, and which event would you skip? Why is before insert a poor choice here?
Show answer
Subscribe to after insert, after delete and after undelete. Use after update too if a Contact can move to a different Account. The count depends on the saved final state, which is only certain in after events. A before insert trigger runs before the record is saved, so the save could still fail and leave the count wrong, and the new Contact has no Id yet. You can skip all before events, because you are not changing the Contact itself.
Exercise
A single upsert call sends 150 Accounts to Salesforce. Sixty of them match existing records, and ninety are new. Which events fire, and how many records does each receive?
Show answer
The insert events (before insert and after insert) fire with the 90 new records in Trigger.new. The update events (before update and after update) fire with the 60 existing records. All 150 records fit in one chunk of up to 200, so each event runs once, but with its own subset of records.