Your First Trigger
By the end of this lesson, you'll be able to:
- Write a complete, working trigger from scratch
- Combine trigger context variables with real business logic
- Trace through what the trigger does for a specific insert scenario
Prerequisites: "Trigger Context Variables"
The scenario
A sales team wants every new Opportunity with an Amount over R100,000 automatically flagged as high-priority by setting a custom Priority__c field to 'High' — without a sales rep needing to remember to set it manually every time.
The complete trigger
trigger OpportunityTrigger on Opportunity (before insert) {
for (Opportunity opp : Trigger.new) {
if (opp.Amount != null && opp.Amount > 100000) {
opp.Priority__c = 'High';
}
}
}
trigger OpportunityTrigger on Opportunity (before insert) {—before insert(Lesson 2 — modifying a field, so it must run before the save).for (Opportunity opp : Trigger.new) {—Trigger.new(Lesson 3 — the records being inserted).if (opp.Amount != null && opp.Amount > 100000) {— a plainifstatement (Module 6) applying the actual business rule.opp.Priority__c = 'High';— flags high-value deals automatically.}— closes theif.}— closes the loop.}— closes the trigger.
Tracing through a specific insert
Opportunity opp = new Opportunity(Name = 'Big Deal', Amount = 150000, StageName = 'Prospecting', CloseDate = Date.today());
insert opp;
System.debug(opp.Priority__c); // 'High'
Opportunity opp = new Opportunity(Name = 'Big Deal', Amount = 150000, StageName = 'Prospecting', CloseDate = Date.today());— a new opportunity,Amountwell over the threshold.insert opp;— triggersOpportunityTriggerautomatically; inside it,Trigger.newcontainsopp;opp.Amount(150000) is greater than 100000, soPriority__cgets set to'High'before the actual save.- (blank line)
System.debug(opp.Priority__c);— logs'High'— the inserted record ends up withPriority__calready correctly populated, with zero extra code required at the call site.
Exercise
Write a before insert trigger on Case that sets a custom field Is_Urgent__c to true whenever the Case's Priority field equals 'High'.
Show hint
if (c.Priority == 'High') { c.Is_Urgent__c = true; }
Your First Trigger Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
This lesson writes one complete, working trigger end to end, combining everything from this module's first three lessons into a real, useful piece of automation.