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';
        }
    }
}

Every piece here has already been covered: before insert (Lesson 2 — modifying a field, so it must run before the save), Trigger.new (Lesson 3 — the records being inserted), and a plain if statement (Module 6) applying the actual business rule.

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'

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 — 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; }

APEX

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.