Development questions
Why is using a simple static Boolean flag to prevent recursion dangerous when processing more than 200 records?
Triggers process records in chunks of 200. A static variable lives for the whole transaction, so after the first chunk sets hasRun = true, chunks 2, 3... in the same transaction see the flag and skip all logic, leaving records 201+ unprocessed (silently).
Fix: track processed record Ids in a static Set<Id> and process only Ids not yet in the set. For updates, you can also reprocess a record only if relevant fields changed.
apex
public static Set<Id> processed = new Set<Id>();
for (Account a : Trigger.new) {
if (processed.add(a.Id)) { /* process */ }
}
apex-triggertriggerrecursionbulk
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?