Sub topic 3
Detecting Changed Fields with `oldMap`
Assume you know basic Apex syntax, collections, SOQL, DML, and governor limits. This chapter focuses on update triggers and the patterns that keep them safe in bulk operations.
Detecting Changes with `oldMap`
Trigger.oldMap is a map from record Id to the record’s previous version. Compare it with Trigger.new to run logic only when a field changes.
trigger OpportunityTrigger on Opportunity (before update) {
for (Opportunity opp : Trigger.new) {
Opportunity oldOpp = Trigger.oldMap.get(opp.Id);
if (opp.StageName != oldOpp.StageName &&
opp.StageName == 'Closed Won') {
opp.CloseDate = Date.today();
}
}
}Rejecting Invalid Records
Call addError to stop a record from being saved. In a before trigger, validate records before the database operation completes.
trigger AccountDeleteGuard on Account (before delete) {
for (Account accountRecord : Trigger.old) {
if (accountRecord.AnnualRevenue != null &&
accountRecord.AnnualRevenue > 1000000) {
accountRecord.addError(
'High-revenue accounts cannot be deleted.'
);
}
}
}Bulk-Safe Trigger Logic
Salesforce can process up to 200 records in one trigger batch. Write one loop for all records, collect results, and perform one DML statement outside the loop. Never put SOQL or DML inside a record loop.
Selecting the Operation
Trigger.operationType returns a System.TriggerOperation value. A switch keeps several events in one trigger readable.
switch on Trigger.operationType {
when BEFORE_INSERT {
System.debug('Preparing new records');
}
when AFTER_UPDATE {
System.debug('Processing updated records');
}
when else {
System.debug('Unhandled operation');
}
}Recursion and Handler Classes
DML performed by a trigger can fire another trigger execution. A static variable lasts for the current transaction and can guard logic.
public class TriggerGuard {
private static Boolean hasRun = false;
public static Boolean shouldRun() {
if (hasRun) return false;
hasRun = true;
return true;
}
}
public class AccountHandler {
public static void afterUpdate(List<Account> accounts) {
// Bulk-safe business logic belongs here.
}
}The trigger should be a small router:
trigger AccountTrigger on Account (after update) {
if (TriggerGuard.shouldRun()) {
AccountHandler.afterUpdate(Trigger.new);
}
}Order of Execution
Salesforce runs before triggers before validation and database save. After triggers run after the record has an Id and the save begins. Follow-up DML can start another order-of-execution cycle, so keep handlers bulk-safe and use recursion guards only when the design requires them.
Exercise
Which collection should an update trigger compare with Trigger.new to detect a prior field value?
Show answer
Compare each record in Trigger.new with the matching record from Trigger.oldMap.