Sub topic 1
What an Apex Trigger Is and When It Fires
Prerequisites
This chapter assumes you know the following:
- Basic Apex syntax: classes, methods, and collections such as
List,Set, andMap. - What Salesforce objects and records are.
- What the DML operations are: insert, update, delete, and undelete.
- That Salesforce enforces governor limits, which cap the resources one transaction can use.
What a trigger is
An Apex trigger is a block of code that Salesforce runs automatically when a record is saved, changed, deleted, or restored. You don't call it. You declare which object and which events it listens to, and the platform runs it at the right moment inside the same transaction as the DML operation.
A trigger is declared with the trigger keyword, a name, the object, and a list of events.
trigger AccountTrigger on Account (before insert, after insert) {
System.debug('Records in this batch: ' + Trigger.size);
}This trigger runs once for each batch of Account records that is inserted. It does not run once for each record. Salesforce passes records to a trigger in batches of up to 200, so a single run can handle many records at once. Later chapters rely on this fact.
The seven events
A trigger can subscribe to seven events. Each one combines a timing (before or after) with a DML operation.
| Event | When it runs | Typical use |
|---|---|---|
| `before insert` | Before new records are written | Set defaults, validate |
| `before update` | Before changes are written | Adjust field values, validate |
| `before delete` | Before records are deleted | Block deletion |
| `after insert` | After new records are saved | Create related records |
| `after update` | After changes are saved | Update related records |
| `after delete` | After records are deleted | Clean up related data |
| `after undelete` | After records are restored from the Recycle Bin | Rebuild related data |
The choice between before and after matters:
- In a before event, the records are not saved yet. You can change field values on
Trigger.newdirectly, and Salesforce saves your changes without an extra DML statement. The record has no Id yet onbefore insert. - In an after event, the records are saved and have Ids, but the values in
Trigger.neware read-only. To change the same record again you need a separate DML statement. After events are the right place to create or update other records that refer to the saved record.
Where a trigger sits in a save
A trigger is one step in a longer sequence. When a user saves a record, Salesforce runs system validation, before triggers, custom validation, the save to the database, after triggers, and then other automation such as flows. Finally it commits the transaction. If anything throws an unhandled exception, the whole transaction rolls back.
This is a simplified view. The full order of execution includes more steps, such as workflow rules and flows, but this version is enough to choose between before and after.
Common errors
- Changing
Trigger.newin an after event. Salesforce raises an error because the records are read-only there. Make the change in a before event or use DML on a copy of the record. - Reading an Id in
before insert. New records have no Id yet, soacc.Idisnull. - Writing for one record. Code that assumes
Trigger.newholds one record works in a manual test and fails during a data load of 200 records. - Listing events you do not use. Each event you subscribe to adds a place where code can run. Subscribe to what you need, and see the later chapters for how to organize it.
Exercise
A trigger must set a default value in the Description field of each new Account, and it must also create a follow-up Task linked to each new Account. Which event should each piece of work use, and why?
Show answer
Set the Description in before insert, because the record is not yet saved and changes to Trigger.new are written without extra DML. Create the Task in after insert, because the Task needs the Account's Id, which exists only after the Account is saved.