Drills › Automate with triggers
Move Opportunity logic to a handler
Automate with triggers · Intermediate · 15 min · Runs in your Salesforce Developer org · Apex Path
Scenario. A sales trigger has grown hard to read. The team wants the trigger to only pick the event, and a handler class to hold the rules.
Move the logic out of a busy Opportunity trigger into beforeInsert and beforeUpdate handler methods.
What you will learn
A trigger should say when work runs, and a handler what it does. This trigger mixes both:
for (Opportunity opp : Trigger.new) {
Boolean fresh = Trigger.isInsert && String.isBlank(opp.Description);
Boolean moved = Trigger.isUpdate
&& opp.StageName != Trigger.oldMap.get(opp.Id).StageName;
if (fresh || moved) {
opp.Description = 'Stage: ' + opp.StageName;
}
}
Gotcha. A class is not bulk safe by itself. Each method must loop over all records.
The task
Move the busy trigger's logic into the handler's beforeInsert and beforeUpdate methods. The provided trigger already calls them from a switch on Trigger.operationType.
Examples:
- insert, Stage
Prospecting, no Description →Stage: Prospecting - insert with Description
Imported→ staysImported - update Stage
Prospecting→Needs Analysis→Stage: Needs Analysis
Requirements:
- In
beforeInsert, give each blank Description the textStage:plus that record's StageName. - In
beforeUpdate, when a record's StageName changed (compare witholdMap), set Description toStage:plus the new StageName, even if it had text. - Leave every other record alone.
- Loop over every record and build the text from that record's own StageName.
Starter code
public class AS_18655177781B_OpportunityHandler {
public static void beforeInsert(List<Opportunity> records) {
}
public static void beforeUpdate(List<Opportunity> records, Map<Id, Opportunity> oldMap) {
}
}
When it passes
New Opportunities get a label from their own stage, stage changes replace the label, other edits keep their text, and 200 records work for both events.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.
‹ Mark parent Accounts in bulk · Require a Contact email domain ›