Skip to content
Tutorials Center
My learning

Topics

Lesson 15 of 36 ยท Triggers

Apex Trigger Basics

Learn what Apex triggers are, the trigger syntax, before and after triggers, the seven events, when to use each, and the order of execution, with Java stand-ins.

A trigger is Apex code that runs automatically when records change. Save an Account, delete a Contact, update an Opportunity: if there is a trigger on that object, it fires. Triggers are how you enforce rules and keep data consistent no matter where a change comes from: the UI, an import, an API call or another piece of code.

Triggers only exist inside a Salesforce org, so real trigger code is shown read-only. The runnable examples are Java stand-ins that model the firing order and the before/after difference.

Syntax

A trigger belongs to one object and lists the events it responds to:

Java
trigger AccountTrigger on Account (before insert, before update, after insert) {
    // code runs when any of these events happens
}

Rules:

  • One trigger per object is the accepted best practice. Several triggers on one object run in no guaranteed order.
  • Triggers are saved as .trigger files with a .trigger-meta.xml partner.
  • Name them ObjectNameTrigger, for example AccountTrigger.

The seven events

Event When it fires
before insert Before new records are saved
before update Before changes to existing records are saved
before delete Before records are deleted
after insert After new records are saved (Ids exist)
after update After changes are saved
after delete After records are deleted
after undelete After records come back from the Recycle Bin

There is no "before undelete".

Before versus after

This choice is the most important design decision in a trigger.

Before triggers run before the record is written to the database. You can change fields on the records in the trigger and they are saved automatically with no DML needed. Use before triggers to:

  • validate or reject changes (addError)
  • set or normalise field values (default a field, format a phone number)
  • copy data from related records

After triggers run after the record is saved. The record has an Id, and the values are final but read-only in the trigger. Use after triggers to:

  • create or update other records that need the new record's Id
  • make callouts or enqueue background jobs
  • react to the final saved state
Java
trigger AccountTrigger on Account (before insert, after insert) {
    if (Trigger.isBefore) {
        for (Account a : Trigger.new) {
            if (a.Rating == null) {
                a.Rating = 'Warm';        // no update statement needed
            }
        }
    }
    if (Trigger.isAfter) {
        List<Task> tasks = new List<Task>();
        for (Account a : Trigger.new) {
            tasks.add(new Task(Subject = 'Welcome call', WhatId = a.Id));   // Id exists now
        }
        insert tasks;
    }
}

If you try to change a record in Trigger.new in an after trigger, Salesforce throws "Record is read-only".

What triggers the trigger?

Any data change on that object: record edit pages, imports through Data Loader, REST/SOAP API calls, flows, other Apex, and even a mass update done by a user in a list view. This is why triggers must handle many records at once: a data import may send up to 200 records per trigger call. Bulkification is a whole lesson later.

The order of execution (short version)

When a record is saved, Salesforce does roughly this:

  1. Run system validation and before-save flows.
  2. Run before triggers.
  3. Run custom validation rules.
  4. Save the record (not yet committed).
  5. Run after triggers.
  6. Run assignment, auto-response, workflow and after-save flows (a flow that updates fields may cause triggers to run again).
  7. Commit.
flowchart TD
    A["Save request"] --> B["Before-save flows"]
    B --> C["Before triggers"]
    C --> D["Validation rules"]
    D --> E["Write to database"]
    E --> F["After triggers"]
    F --> G["After-save flows and rules"]
    G --> H["Commit"]

Before triggers can edit the record for free; after triggers see the saved Id.

A stand-in for before and after

This Java model has a save method that fires before and after hooks. The before hook edits the record; the after hook sees the assigned Id and creates a related record.

Java Stand-in (Java): before and after trigger hooks

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Stopping a save with addError

A before trigger can block a save with a message the user sees. addError can be placed on the record or on a single field:

Java
trigger OpportunityTrigger on Opportunity (before insert, before update) {
    for (Opportunity o : Trigger.new) {
        if (o.Amount != null && o.Amount < 0) {
            o.Amount.addError('Amount cannot be negative');
        }
    }
}

With a normal DML call, one record with an error fails the whole batch; with partial success (allOrNone=false) only the flagged records fail.

Java Stand-in (Java): addError blocks a record

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

When not to use a trigger

Triggers are powerful but hard to maintain. For a simple "when X, set Y" rule, a record-triggered Flow is easier to build and change. Choose a trigger when you need complex logic, heavy bulk processing or fine control over order and errors.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. In which trigger type can you change a record's fields without a DML statement?

    Changes made to Trigger.new in a before trigger are saved automatically. After triggers see read-only records.
  2. 2. Why do you use an after trigger to create a related Task for a new Account?

    The Id is assigned on save, so related records that refer to it are created in an after trigger.
  3. 3. How many triggers per object is the recommended practice?

    Multiple triggers on one object run in no guaranteed order, so use one trigger and delegate to a handler.
  4. 4. Which event does NOT exist?

    There are before triggers for insert, update and delete, and after triggers for those plus undelete.

Summary

  • A trigger is Apex that runs automatically on insert, update, delete or undelete.
  • Before triggers edit and validate records for free; after triggers react to saved records with Ids.
  • Use one trigger per object and expect up to 200 records per call.
  • addError blocks a record with a message.
  • Prefer record-triggered Flows for simple rules.

Next: Trigger Context Variables