Sub topic 1
Anatomy of an Apex trigger
An Apex trigger is code that Salesforce runs automatically when records of one object are inserted, updated, deleted, or undeleted. This chapter covers the structure of a trigger: its declaration, its body, its metadata, and how Salesforce calls it. Later chapters cover each event and each context variable in detail.
Prerequisites
This chapter assumes you already have the following:
- Basic Apex syntax: variables, loops, and the collection types List, Set, and Map.
- Salesforce data model basics: objects, fields, records, and record Ids.
- Familiarity with DML statements (
insert,update,delete) and SOQL queries. - Awareness that governor limits cap what one transaction may do.
You also need a Developer Edition org or a sandbox where you can create Apex code. You can't edit triggers directly in production.
What a trigger is
A trigger is a piece of Apex attached to a single object, such as Account or a custom object. You don't call it. Salesforce calls it when a matching data event happens, whether the change comes from the UI, an API call, a Flow, a data import, or other Apex.
Triggers fit requirements that declarative tools handle badly. Examples are complex logic across several related objects, or logic that must run for every save path without exception.
The declaration
Every trigger has the same header shape:
trigger TriggerName on ObjectName (trigger_event_list) {
// trigger body
}The parts are:
| Part | Meaning |
|---|---|
| `trigger` | Keyword that starts the declaration. Use it instead of `class`. |
| `TriggerName` | A name you choose. By convention it combines the object and the word Trigger, such as `AccountTrigger`. |
| `on ObjectName` | The one object this trigger is attached to. Standard and custom objects both work. |
| Event list | One or more events, separated by commas, that cause the trigger to run. |
| Body | The Apex statements that run when an event matches. |
Here is the smallest useful trigger from this plan:
trigger AccountTrigger on Account (before insert, before update) {
for (Account a : Trigger.new) {
if (String.isBlank(a.Description)) {
a.Description = 'Set by AccountTrigger';
}
}
}This trigger listens to two events on Account: before insert and before update. If either occurs, the body runs. Trigger.new is a context variable that holds the records being saved. The loop fills in a blank Description. No update statement is needed, because in a before event the changes to those records are saved along with the original operation.
Event names
Each event name combines a timing word and a DML operation. There are seven valid combinations:
before insert,before update,before deleteafter insert,after update,after delete,after undelete
Timing words appear only in this fixed list. There is no before undelete. The next chapter walks through the seven events and when to choose each.
You can list any subset of events in the declaration. The trigger body runs only for those. If you declare (before insert), an update never starts the trigger.
The body
The body is ordinary Apex with a few differences from a class:
- Salesforce supplies the implicit
Triggerclass. Its static properties describe the current invocation, for exampleTrigger.newandTrigger.isInsert. - You write statements directly in the body. A trigger is not a class, so it doesn't declare methods. You can't declare a class or static members in it either. This is why reusable logic and the recursion guard shown later live in separate Apex classes.
- A trigger can call methods on other classes, and that's the normal way to keep a trigger short.
Because one trigger can serve several events, the body often checks which event fired before acting. Later chapters cover that branching with Trigger.isInsert, Trigger.isBefore, and Trigger.operationType.
How Salesforce calls a trigger
A trigger doesn't run once per record. Salesforce processes records in batches of up to 200, and each batch is one trigger invocation. Insert 500 accounts with a data load and the trigger runs in three invocations: 200, 200, and 100 records. Those invocations share the same transaction and the same governor limits.
This is the reason every example loops over Trigger.new. Code that assumes one record, such as Trigger.new[0], silently ignores the rest.
If an unhandled exception occurs in any invocation, or addError is called on a record, Salesforce rolls back the whole transaction. For addError, a later chapter explains when that rolls back the entire batch and when it affects only the flagged records.
Metadata and files
A trigger is stored as two files when you use Salesforce DX or VS Code:
AccountTrigger.triggerholds the source code.AccountTrigger.trigger-meta.xmlholds the metadata.
<?xml version="1.0" encoding="UTF-8"?>
<ApexTrigger xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>62.0</apiVersion>
<status>Active</status>
</ApexTrigger>Two values matter:
apiVersionpins the trigger to a platform API version. Behavior can differ slightly between versions, so keep it consistent with your classes.statusisActiveorInactive. An inactive trigger exists but never fires. This gives you a way to switch a trigger off without deleting it.
You can create a trigger from the Developer Console (File > New > Apex Trigger), from VS Code with the Salesforce extensions, or in Setup by opening the object and selecting Triggers. The Developer Console and Setup editors work only in sandboxes and Developer orgs. In production you deploy the trigger together with its tests.
One trigger per object
Salesforce lets you attach many triggers to the same object and event. It doesn't guarantee the order in which they run. If two triggers set the same field, the outcome depends on an order you can't control.
The usual practice is therefore one trigger per object, covering all the events you need. The trigger decides which event fired and passes the work to a handler class. A later chapter builds that handler.
Testing a trigger
Deploying to production requires at least 75% overall Apex test coverage, and every trigger must have some coverage. You test a trigger by performing the DML that fires it:
@IsTest
private class AccountTriggerTest {
@IsTest
static void setsDescriptionWhenBlank() {
Account a = new Account(Name = 'Test Account');
insert a;
Account saved = [SELECT Description FROM Account WHERE Id = :a.Id];
Assert.areEqual('Set by AccountTrigger', saved.Description);
}
}The test never calls the trigger. The insert fires it, as in production. A better test also inserts 200 or more records in one statement to prove the logic is bulk-safe.
Common mistakes
- Assuming one record. Always loop over the collection.
- Declaring events you don't use. Extra events make the trigger run for no reason and make the logic harder to read.
- Several triggers on one object. Execution order is undefined.
- Putting all logic in the trigger body. Long trigger bodies are hard to test and reuse. Move logic into classes once it grows.
- Forgetting that triggers run for every save path. Data loads, integrations, and other automation all fire your trigger, so it must not assume a UI user.
Exercise
A data load inserts 450 Account records in one operation, and your AccountTrigger on Account (before insert, before update) is active. How many times does the trigger run, how many records does Trigger.new hold in each run, and why does the code have to loop?
Show answer
The trigger runs three times, in the same transaction. Trigger.new holds 200, 200, and 50 records, because Salesforce passes records to the trigger in chunks of up to 200. The code must loop over Trigger.new because each invocation can contain many records. Code that reads only Trigger.new[0] would skip the other records in every chunk.
Exercise
A teammate adds a second trigger, AccountTrigger2 on Account (before insert), that also sets Description. What problem does this create, and what is the recommended fix?
Show answer
Salesforce doesn't guarantee the order in which multiple triggers on the same object and event run, so the final Description value is unpredictable. The fix is to keep one trigger per object and move the combined logic into a handler class that the trigger calls.