Sub topic 1
Trigger Events and Context Variables
Prerequisites
This chapter assumes you can do the following:
- Read and write basic Apex, including
List,Set, andMap. - Write a simple trigger on a standard object such as Account.
- Use DML statements such as
insertandupdate. - Recognize that Salesforce enforces governor limits per transaction.
You don't need to know anything about recursion yet. This chapter sets up the vocabulary the rest of the tutorial relies on. To stop a trigger from running again, you first have to know which event is running, which records it holds, and whether those records can be changed.
Why context matters for recursion
A trigger runs in response to a database event. Every recursion fix in later chapters depends on the answers to three questions:
- Which event caused this run: before or after, insert, update, delete, or undelete?
- Which records does the trigger hold, and are they old values, new values, or both?
- Can the trigger change those records directly, or only through a new DML statement?
Apex answers these with trigger events and context variables.
The seven trigger events
A trigger declares the events it listens to. Each event is a combination of a timing (before or after) and an operation.
| Event | When it runs |
|---|---|
| `before insert` | Before new records are saved. They have no Id yet. |
| `before update` | Before changed values are saved. |
| `before delete` | Before records are deleted. |
| `after insert` | After new records are saved, so they have Ids. |
| `after update` | After changed values are saved. |
| `after delete` | After records are deleted. |
| `after undelete` | After records are restored from the Recycle Bin. |
There is no before undelete. Merge and upsert don't add events. An upsert fires the insert or update events, depending on whether each record exists.
Before triggers run before the record is written to the database, so they can still change it. After triggers run once the record is saved, so the record is read-only. This distinction is the basis of the first and best recursion fix, covered in the next chapters.
The dotted arrow is the recursion path. If an after trigger issues DML on the same kind of record, the save process begins again inside the same transaction.
Context variables
Apex provides context variables through the Trigger class. They describe the current run and exist only inside a trigger, or inside code the trigger calls.
Variables that tell you which event is running:
| Variable | Type | Meaning |
|---|---|---|
| `Trigger.isBefore` | Boolean | True in a before trigger. |
| `Trigger.isAfter` | Boolean | True in an after trigger. |
| `Trigger.isInsert` | Boolean | True for an insert operation. |
| `Trigger.isUpdate` | Boolean | True for an update operation. |
| `Trigger.isDelete` | Boolean | True for a delete operation. |
| `Trigger.isUndelete` | Boolean | True for an undelete operation. |
| `Trigger.operationType` | `System.TriggerOperation` | An enum such as `BEFORE_INSERT` or `AFTER_UPDATE`. |
| `Trigger.isExecuting` | Boolean | True when the current code was called from a trigger. |
Variables that hold the records:
| Variable | Type | Contents |
|---|---|---|
| `Trigger.new` | `List<SObject>` | The new versions of the records. |
| `Trigger.old` | `List<SObject>` | The old versions of the records. |
| `Trigger.newMap` | `Map<Id, SObject>` | New versions keyed by Id. |
| `Trigger.oldMap` | `Map<Id, SObject>` | Old versions keyed by Id. |
| `Trigger.size` | Integer | The total number of records in this invocation, old and new. |
Which variables exist in which event
Not every variable is populated in every event. Reading one that isn't available gives you null, and using that null causes a NullPointerException.
| Event | `new` | `newMap` | `old` | `oldMap` |
|---|---|---|---|---|
| `before insert` | Yes | No | No | No |
| `before update` | Yes | Yes | Yes | Yes |
| `before delete` | No | No | Yes | Yes |
| `after insert` | Yes | Yes | No | No |
| `after update` | Yes | Yes | Yes | Yes |
| `after delete` | No | No | Yes | Yes |
| `after undelete` | Yes | Yes | No | No |
Two rules cover most of this table:
- Insert and undelete have only new values. Delete has only old values. Update has both.
newMapneeds Ids, and records inbefore insertdon't have any yet. That is whyTrigger.newMapisnullthere.
What you may modify
Records in Trigger.new can be changed only in before triggers. In an after trigger, assigning a field on a Trigger.new record throws a "Record is read-only" error. Trigger.old and Trigger.oldMap are always read-only.
Using the variables in code
Declare only the events your logic needs. A trigger that lists every event but handles two of them is harder to read and runs more often than it should.
This trigger uses Trigger.operationType in a switch statement. The branch you enter tells you which variables are safe to read.
trigger AccountTrigger on Account (before insert, before update, after update) {
switch on Trigger.operationType {
when BEFORE_INSERT {
for (Account acc : Trigger.new) {
// acc.Id is null here, and Trigger.newMap is null
acc.Description = 'Created';
}
}
when BEFORE_UPDATE {
for (Account acc : Trigger.new) {
Account oldAcc = Trigger.oldMap.get(acc.Id);
if (acc.Rating != oldAcc.Rating) {
acc.Description = 'Rating changed';
}
}
}
when AFTER_UPDATE {
System.debug('Saved ' + Trigger.size + ' accounts');
}
}
}Both before branches change acc directly, with no DML statement. That is allowed because the records are not yet saved. The AFTER_UPDATE branch only reads values.
The same logic works with the Boolean variables. They are often better when one trigger handles several events with shared code:
trigger AccountTrigger on Account (before insert, before update) {
for (Account acc : Trigger.new) {
if (Trigger.isInsert) {
acc.Description = 'Created';
} else if (acc.Rating != Trigger.oldMap.get(acc.Id).Rating) {
acc.Description = 'Rating changed';
}
}
}The Trigger.isInsert check protects the oldMap call. On insert, Trigger.oldMap is null, so calling get on it would fail.
Records arrive in chunks
When a single operation affects many records, Salesforce does not hand all of them to the trigger at once. It splits them into chunks of up to 200 records. For example, an update of 450 accounts runs the trigger three times, with 200, 200, and 50 records. All three runs belong to one transaction.
Trigger.size and the length of Trigger.new reflect the current chunk, not the whole operation. Code that assumes it sees every record in one run will behave correctly in a small test and wrongly in production. This matters in a later chapter, where a simple recursion guard can skip the second and third chunks.
Common errors
- Reading
Trigger.oldMapon insert. It isnull. CheckTrigger.isUpdateorTrigger.isInsertfirst. - Using
Trigger.newMapinbefore insert. It isnullbecause there are no Ids yet. Loop overTrigger.newinstead. - Looping over
Trigger.newin a delete trigger. It isnull. UseTrigger.old. - Assigning fields in an after trigger. This throws a read-only error. Move simple field changes to a before trigger.
- Treating
Trigger.sizeas the full operation size. It covers one chunk of up to 200 records.
How this connects to recursion
Recursion happens when a trigger's own DML starts a new save for the same object. The context variables give you three tools against it:
- The timing flags tell you whether a direct field change is possible, which avoids the extra DML.
Trigger.oldMaplets you compare values and act only on real changes.- The record Ids in
Trigger.neware what a guard can later remember, so each record is handled once.
The next chapters build on these three tools.
Exercise
A trigger on Account listens to before insert. It contains Trigger.newMap.get(acc.Id) inside a loop over Trigger.new. What happens, and how do you fix it?
Show answer
Trigger.newMap is null in before insert because the records have no Ids yet, so the code throws a NullPointerException. Use the acc variable from the loop directly instead of looking it up in a map.
Exercise
You need to set Description on an Account whenever it is updated. Why should this live in a before update trigger rather than an after update trigger?
Show answer
In a before update trigger you can assign acc.Description directly on the records in Trigger.new, and Salesforce saves the value with no DML statement. In an after update trigger the records are read-only, so you would need a separate update, which can fire the trigger again.
Exercise
An update statement changes 450 Account records. How many times does the trigger run, and what is Trigger.size in each run?
Show answer
The trigger runs three times in one transaction. Trigger.size is 200, 200, and 50, because records are processed in chunks of up to 200.