Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 36 ยท Triggers

Trigger Context Variables

Use Trigger.new, Trigger.old, Trigger.newMap, Trigger.oldMap and the isInsert, isBefore and operationType flags to detect what changed in an Apex trigger.

Inside a trigger you do not receive parameters. Instead Salesforce provides a set of built-in variables on the Trigger class: the records involved, the old versions, and flags that tell you which event fired. Mastering them lets you write triggers that react only to real changes, which saves processing time and avoids infinite loops.

Triggers run only inside an org, so the real code is read-only. The Java stand-ins model the context variables with ordinary collections.

The record variables

Variable Type Available in
Trigger.new List<SObject> of new versions insert, update, undelete
Trigger.old List<SObject> of old versions update, delete
Trigger.newMap Map<Id, SObject> of new versions after insert, before/after update, after undelete
Trigger.oldMap Map<Id, SObject> of old versions update, delete

Why are some missing? A record has no old version on insert and no new version on delete. Also, newMap is not available in before insert because the records have no Ids yet.

Java
trigger AccountTrigger on Account (before update) {
    for (Account newAcc : Trigger.new) {
        Account oldAcc = Trigger.oldMap.get(newAcc.Id);
        if (newAcc.Industry != oldAcc.Industry) {
            System.debug('Industry changed from ' + oldAcc.Industry + ' to ' + newAcc.Industry);
        }
    }
}

Trigger.oldMap.get(newAcc.Id) pairs each new record with its old version. This is the standard way to detect a change.

The flag variables

Variable True when
Trigger.isInsert isUpdate isDelete isUndelete The operation matches
Trigger.isBefore isAfter Before or after phase
Trigger.isExecuting Code is running in a trigger context
Trigger.operationType An enum such as System.TriggerOperation.BEFORE_UPDATE
Trigger.size Number of records in this call

The most readable way to branch is a switch on operationType:

Java
trigger OpportunityTrigger on Opportunity (before insert, before update, after update) {
    switch on Trigger.operationType {
        when BEFORE_INSERT { /* defaults */ }
        when BEFORE_UPDATE { /* validation */ }
        when AFTER_UPDATE  { /* follow-up work */ }
    }
}

A frequent need: has this field changed?

Without comparing new to old, a trigger would run its logic for every save, even when nothing relevant changed. This pattern keeps it tight:

Java
List<Opportunity> wonNow = new List<Opportunity>();
for (Opportunity opp : Trigger.new) {
    Opportunity old = Trigger.isUpdate ? Trigger.oldMap.get(opp.Id) : null;
    Boolean becameWon = opp.StageName == 'Closed Won'
                     && (old == null || old.StageName != 'Closed Won');
    if (becameWon) {
        wonNow.add(opp);
    }
}

For an insert, old is null, and any record already Closed Won counts as newly won.

Stand-in: new versus old

The Java stand-in builds a map of old versions and detects which records changed their stage. It models Trigger.new (list) and Trigger.oldMap (map by id).

Java Stand-in (Java): detect changed records with oldMap

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.

Using operationType in a stand-in

The following stand-in dispatches on an enum, the way a handler switch on Trigger.operationType does.

Java Stand-in (Java): dispatch by operation type

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.

Preventing recursion

When your trigger updates records, those updates can fire the same trigger again, and again. Two defences:

  1. Compare old and new so work happens only on real changes.
  2. Use a static variable as a guard, because static variables last for the whole transaction:
Java
public class TriggerGuard {
    public static Boolean hasRun = false;
}

// in the trigger
if (TriggerGuard.hasRun) { return; }
TriggerGuard.hasRun = true;

A simple boolean is blunt: it skips the second chunk of 200 records in a big import. A better guard stores a Set of record Ids already processed, and skips only those.

Other useful details

  • Trigger.new records in a before trigger can be edited; the list itself cannot be added to or removed from.
  • Trigger.size helps log how big the batch was.
  • In before delete use Trigger.old (and Trigger.oldMap) to see what is about to vanish; you can call addError to stop it.

Common mistakes

  • Reading Trigger.newMap in before insert (it is null).
  • Reading Trigger.old on insert.
  • Running expensive logic every time instead of on real changes.
  • Updating the same records in an after trigger, causing recursion.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which variable holds the old versions of updated records keyed by Id?

    Trigger.oldMap maps each record Id to its version before the update.
  2. 2. Which context variable is not available in before insert?

    newMap needs record Ids, which do not exist before the first save.
  3. 3. How do you check that a field changed during an update?

    Comparing each new record to its old version in oldMap is the standard approach.
  4. 4. Why is a single static Boolean a weak recursion guard?

    Large operations are processed in chunks of 200; a Boolean would skip every chunk after the first. A Set<Id> of processed records is more precise.

Summary

  • Trigger.new/old/newMap/oldMap hold the records; which ones exist depends on the event.
  • isInsert, isBefore and operationType tell you which event fired.
  • Compare new with oldMap to run logic only on real changes.
  • Guard against recursion with change checks or a static Set<Id>.

Next: Bulkification in Triggers