Sub topic 1
Trigger events and context variables
Prerequisites
Assume you know basic Apex syntax, collections, DML statements, and simple Salesforce triggers. A trigger is Apex code that runs when records are inserted, updated, deleted, or restored.
Trigger events and context variables
The trigger event tells you what happened. Common events include before insert, after insert, before update, and after update. Salesforce provides context variables that describe the current operation:
Trigger.newcontains the incoming record versions.Trigger.oldcontains the previous versions.Trigger.newMapandTrigger.oldMapprovide records by Id.Trigger.isBefore,Trigger.isAfter, andTrigger.isUpdateidentify the timing and operation.
Use Trigger.new records in a before trigger when you need to change field values before Salesforce saves them.
Order of execution and why triggers can run twice
Salesforce runs several automation steps during a save. A trigger can run, another automation step can change the record, and Salesforce can run update automation again. An after trigger can also issue DML that starts another save cycle.
How a trigger ends up calling itself
This after trigger updates the same Account that caused it to run:
trigger AccountTrigger on Account (after update) {
List<Account> recordsToUpdate = new List<Account>();
for (Account acc : Trigger.new) {
recordsToUpdate.add(new Account(
Id = acc.Id,
Description = 'Reviewed'
));
}
update recordsToUpdate;
}The update statement starts another Account update. The trigger runs again and issues another update. Salesforce eventually stops the transaction with a trigger-depth error.
Prefer before triggers: change records without DML
When the trigger only needs to set fields on the records being saved, use a before trigger. Assigning a value to Trigger.new does not require an extra DML statement, so it does not create this recursion.
Run logic only when a field actually changed
Compare the new and old values. This prevents work when an unrelated field changes:
trigger AccountTrigger on Account (before update) {
for (Account acc : Trigger.new) {
Account oldAcc = Trigger.oldMap.get(acc.Id);
if (acc.Rating != oldAcc.Rating) {
acc.Description = 'Rating changed';
}
}
}Exercise
Why does changing acc.Description in this before trigger not require update acc?
Show answer
Salesforce saves changes made to Trigger.new as part of the current save operation.