Intermediate 25 min read

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';
        }
    }
}
  1. trigger OpportunityTrigger on Opportunity (before insert) { — before insert (Lesson 2 — modifying a field, so it must run before the save).
  2. for (Opportunity opp : Trigger.new) { — Trigger.new (Lesson 3 — the records being inserted).
  3. if (opp.Amount != null && opp.Amount > 100000) { — a plain if statement (Module 6) applying the actual business rule.
  4. opp.Priority__c = 'High'; — flags high-value deals automatically.
  5. } — closes the if.
  6. } — closes the loop.
  7. } — 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'
  1. Opportunity opp = new Opportunity(Name = 'Big Deal', Amount = 150000, StageName = 'Prospecting', CloseDate = Date.today()); — a new opportunity, Amount well over the threshold.
  2. insert opp; — triggers OpportunityTrigger automatically; inside it, Trigger.new contains opp; opp.Amount (150000) is greater than 100000, so Priority__c gets set to 'High' before the actual save.
  3. (blank line)
  4. System.debug(opp.Priority__c); — logs 'High' — the inserted record ends up with Priority__c already 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; }

Salesforce: ○ Not connected Connect
APEX

Execution Results

Run your code to see the result.

Your First Trigger Quiz

1. Why does OpportunityTrigger check opp.Amount != null before comparing it to 100000?

Log in to submit the quiz and save your score.

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.