Development questions
How do you prevent trigger recursion properly using a Set<Id> of processed record IDs?
Keep a static Set<Id> in the handler. Each time the trigger runs, filter Trigger.new to records whose Id is not yet in the set, process only those, and add them to the set.
apex
public class AccountHandler {
private static Set<Id> processedIds = new Set<Id>();
public void afterUpdate(List<Account> news) {
List<Account> toProcess = new List<Account>();
for (Account a : news) {
if (!processedIds.contains(a.Id)) {
processedIds.add(a.Id);
toProcess.add(a);
}
}
// process toProcess
}
}
This works across 200-record chunks. If a record legitimately must be reprocessed after another change, compare field values instead.
apex-triggertriggerrecursion
More Development questions
- What is an Apex Trigger in Salesforce and when should you use it over Flows?
- What is the difference between before triggers and after triggers?
- Explain all Trigger context variables (isInsert, isUpdate, isDelete, isUndelete, isBefore, isAfter, isExecuting, size, operationType).
- What is the difference between Trigger.new and Trigger.old?
- In which trigger events are Trigger.new and Trigger.newMap available?
- In which trigger events are Trigger.old and Trigger.oldMap available?