Drills › Automate with triggers
Stop recursive Account updates
Automate with triggers · Advanced · 20 min · Runs in your Salesforce Developer org · Apex Path
Scenario. A sync step must stamp each Account after it saves. The stamp is an update to the same Account, which runs the trigger again, so the handler must stop after one pass.
Stamp each updated Account once from an after-update trigger, and use a static Set of Ids to stop the update from running the trigger again and again.
What you will learn
In an after trigger, Trigger.new is read-only. To change those records you must update them, and that update runs the same trigger again. That is when you need a recursion guard: a static Set of the Ids you already handled.
if (handledIds.contains(row.Id)) {
continue;
}
handledIds.add(row.Id);
Gotcha. If a before trigger can make the change, use it: no DML, no recursion. A static guard lasts the whole transaction, so it also skips a later update of the same record.
The task
Complete the handler so each updated Account gets :: synced added to its Description exactly once, using one follow-up update.
Examples:
- Description
Start→Start :: synced - blank Description →
synced - 200 Accounts updated together → each marked once, with one follow-up update
Requirements:
- Skip any Account whose Id is already in
handledIds. Add new Ids before you update. - Read Description from the records in
records. They hold the values that were just saved. - Do not change
records. They are read-only, so buildnew Account(Id = ..., Description = ...)for each one. - Add
:: synced(space, two colons, space) when there is text. Usesyncedwhen it is blank. - Update the new Accounts once, after the loop.
Starter code
public class AS_F6172D398608_RecursionGuard {
private static Set<Id> handledIds = new Set<Id>();
public static void afterUpdate(List<Account> records) {
List<Account> followUps = new List<Account>();
for (Account account : records) {
}
}
}
When it passes
Each updated Account gets exactly one marker built from its new Description. The second trigger run is skipped, and 200 Accounts cost the same DML as one.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.
‹ Require a Contact email domain · Block deleting Accounts with open deals ›