Sub topic 1
What an Apex Trigger Is and When It Fires
Prerequisites
This chapter assumes you already know the following:
- Basic Apex syntax: classes, methods,
List,SetandMap. - Salesforce objects and records, such as Account and Contact.
- The DML operations
insert,update,deleteandundelete. - That governor limits exist and cap what one transaction can do.
You do not need any trigger experience. Later chapters build the handler pattern on top of what you learn here.
What a trigger is
An Apex trigger is a block of code that Salesforce runs automatically when a record is saved, deleted or restored. You do not call a trigger. You declare which object and which events it listens to, and the platform calls it.
A trigger is not a class. It has its own metadata type and its own syntax:
trigger AccountTrigger on Account (before insert, after insert) {
System.debug(Trigger.operationType + ' fired with ' + Trigger.size + ' records');
}The declaration has three parts:
- The keyword
triggerand a name. - The object after
on. This can be a standard object, a custom object, or another supported object type. - A comma-separated list of events in parentheses.
The body runs once for each event that occurs, and it receives a batch of records, not a single record. This is the most important fact about triggers. Every design rule in this tutorial follows from it.
The seven trigger events
A trigger can listen to seven events. Each one pairs a timing (before or after) with a DML operation.
| Event | Fires | Typical use |
|---|---|---|
| `before insert` | Before new records are written | Set defaults, normalize values |
| `after insert` | After new records are written | Create related records |
| `before update` | Before changes are written | Compare old and new, adjust fields |
| `after update` | After changes are written | Update related records |
| `before delete` | Before records are removed | Block deletion |
| `after delete` | After records are removed | Clean up related data |
| `after undelete` | After records are restored from the Recycle Bin | Rebuild related data |
There is no before undelete. You can list any subset of the seven events in one trigger declaration.
Some DML statements map to more than one event:
upsertfires insert triggers for the records it creates and update triggers for the records it updates.mergefires delete triggers for the losing records and update triggers for the winning record.Database.insert,Database.updateand the otherDatabasemethods fire the same triggers as the matching DML statements.
Before versus after
The choice between before and after decides what your code can do.
Before triggers run before the record is saved to the database. You can change field values on the records in Trigger.new directly, and Salesforce saves your changes. You need no DML statement, and you must not add one for the same records. This makes before triggers the right place to set defaults and clean data. On before insert the records have no Id yet, because they have not been saved.
After triggers run once the record has been written. The records now have an Id, so you can use them as parents of new related records. The records in Trigger.new are read-only, and assigning to a field throws a System.FinalException. To change the triggering records in an after trigger, query them again or build new sObject instances with the same Id, then update them with DML. That update fires the update triggers again, which is the cause of the recursion problem covered in a later chapter.
An after trigger can still be rolled back. The changes are not committed until the whole transaction finishes without an unhandled exception.
trigger AccountTrigger on Account (before insert, after insert) {
if (Trigger.isBefore) {
for (Account acc : Trigger.new) {
// Allowed: Trigger.new is editable in a before trigger.
acc.Description = 'Set in before insert';
}
} else if (Trigger.isAfter) {
List<Task> followUps = new List<Task>();
for (Account acc : Trigger.new) {
// acc.Id is populated here, so it can be used as a parent.
followUps.add(new Task(WhatId = acc.Id, Subject = 'Welcome call'));
}
insert followUps;
}
}This trigger is only a demonstration. A trigger written this way has its logic inside the trigger body, which later chapters argue against.
Where a trigger sits in a save
When you save a record, Salesforce runs a long sequence of steps. The exact order is documented in "Triggers and Order of Execution" in the Apex Developer Guide. This diagram shows only the steps that matter here.
Two points follow from the diagram:
- Before triggers run before validation rules. A before trigger can fix a value that a validation rule would otherwise reject.
- Record-triggered flows and workflow field updates run in this sequence too. If they change a record, the update triggers can fire again inside the same transaction. The full order has more steps than shown here, including before-save flows ahead of the before triggers, so consult the Apex Developer Guide when ordering matters.
What starts a trigger
Triggers fire no matter which path saves the data:
- A user editing a record in the Salesforce UI.
- A call through the REST or SOAP API, including Data Loader and other integrations.
- Apex code running DML.
- Other automation that performs DML, such as a flow.
Your trigger cannot tell where the change came from by default. A trigger that is correct for one user saving one record in the UI must still be correct for an integration that loads thousands of records.
Batches of up to 200 records
Salesforce hands records to a trigger in chunks of up to 200. A single DML statement with 201 records runs the trigger more than once for each event, first with 200 records and then with 1.
List<Account> accts = new List<Account>();
for (Integer i = 0; i < 201; i++) {
accts.add(new Account(Name = 'Chunk test ' + i));
}
insert accts;Run this as anonymous Apex with the debug trigger from the start of this chapter deployed. The debug log shows BEFORE_INSERT fired with 200 records followed by AFTER_INSERT fired with 200 records, then the same pair with 1 record.
A trigger invocation is not a transaction. The whole insert is one transaction, so all the chunks share one set of governor limits. If every chunk runs a query, the number of queries adds up across chunks. This is why you should never write a query or a DML statement inside a loop over Trigger.new.
Other edge cases:
- A trigger can fire with a single record, 200 records, or any size in between. Never assume a size.
- A trigger fires only if the DML actually runs. An
updateon an empty list does nothing and fires no trigger. - A trigger on
Accountdoes not run for a change to a different object. A change to a Contact fires only Contact triggers, even if it updates a field on the parent Account through a roll-up.
A first look at context variables
Salesforce gives the trigger body a set of implicit variables on the Trigger class. The next chapter covers them in depth. You need a few now to read the examples:
| Variable | Meaning |
|---|---|
| `Trigger.new` | List of the new versions of the records |
| `Trigger.old` | List of the old versions of the records |
| `Trigger.newMap` | Map of `Id` to new record |
| `Trigger.oldMap` | Map of `Id` to old record |
| `Trigger.operationType` | A `System.TriggerOperation` value such as `BEFORE_INSERT` |
| `Trigger.isBefore`, `Trigger.isAfter` | Whether the trigger is running before or after the save |
| `Trigger.size` | Number of records in this invocation |
Which collections are filled in depends on the event:
Trigger.newis not available in delete triggers, andTrigger.oldis not available in insert or undelete triggers.Trigger.oldMapandTrigger.newMapare not available everywhere either. For example,Trigger.newMapdoes not exist inbefore insert, because the records have noIdyet.- In
before updateyou can compareTrigger.oldMap.get(acc.Id)withaccto find which fields changed.
Common mistakes
- Assuming one record. Code such as
Trigger.new[0]works in the UI and fails or silently skips records in a data load. - Using DML on
Trigger.newin a before trigger. The platform saves your field changes already. A DML statement on those records throws an error. - Editing
Trigger.newin an after trigger. The records are read-only, so the assignment throws aSystem.FinalException. - Relying on
Idinbefore insert. The value isnull. Use an after trigger if you need the new Id. - Listing events you do not handle. A trigger subscribed to events it ignores still runs, and it still costs CPU time.
Summary
- A trigger is code that Salesforce runs automatically on save, delete or undelete.
- There are seven events: before and after for insert, update and delete, plus after undelete.
- Before triggers edit records in place. After triggers see saved records with
Idvalues but cannot editTrigger.new. - Every save path fires triggers, and records arrive in chunks of up to 200 inside one shared transaction.
- Context variables on
Triggerdescribe the records and the event. Which ones are filled in depends on the event.
Exercise
A before insert trigger on Account sets acc.Description in a loop over Trigger.new and then calls update Trigger.new; at the end. What goes wrong, and what is the fix?
Show answer
In a before trigger, Salesforce saves field changes made to Trigger.new records on its own. The explicit update is unnecessary, and DML on those records in a before insert trigger raises an error because the records do not exist in the database yet. The fix is to delete the update statement and keep only the field assignments.
Exercise
You run insert accts; with a list of 450 Accounts, and the Account trigger listens to before insert and after insert. How many chunks does the trigger see, how large is each one, and do the chunks share governor limits?
Show answer
The trigger sees three chunks, of 200, 200 and 50 records, and each chunk runs the before and after events. All three chunks belong to the same transaction, so they share one set of governor limits.