Sub topic 3
Acting Only on Records That Changed
Assume you know Apex classes, sObjects, SOQL, DML, and trigger context variables. This chapter focuses on update logic that remains bulk-safe.
Detecting changed values
Compare Trigger.new with Trigger.oldMap. Trigger.oldMap contains the previous version of each record during update, but it is null during insert. Check the old value before using it.
trigger OpportunityTrigger on Opportunity (after insert, after update) {
OpportunityTriggerHandler.createFollowUpTasks(
Trigger.new,
Trigger.oldMap
);
}
public with sharing class OpportunityTriggerHandler {
public static void createFollowUpTasks(
List<Opportunity> newOpps,
Map<Id, Opportunity> oldMap
) {
List<Task> tasks = new List<Task>();
for (Opportunity opp : newOpps) {
Boolean isWon = opp.StageName == 'Closed Won';
Boolean wasWon = oldMap != null
&& oldMap.get(opp.Id).StageName == 'Closed Won';
if (isWon && !wasWon) {
tasks.add(new Task(
Subject = 'Send welcome package',
WhatId = opp.Id,
OwnerId = opp.OwnerId
));
}
}
if (!tasks.isEmpty()) {
insert tasks;
}
}
}The handler creates a task only when the opportunity enters Closed Won. It performs one DML operation for the whole collection.
Reporting errors per record
addError attaches a validation error to a record or field. With partial-success DML, invalid records fail while valid records can save.
trigger InvoiceLineTrigger on Invoice_Line__c (before insert, before update) {
for (Invoice_Line__c line : Trigger.new) {
if (line.Quantity__c != null && line.Quantity__c < 0) {
line.Quantity__c.addError('Quantity cannot be negative.');
}
}
}Thin triggers and bulk tests
A thin trigger delegates work to a handler. This keeps entry-point code easy to inspect and test. Test the largest normal trigger batch, which is 200 records.
@IsTest
private class OpportunityTriggerTest {
@IsTest
static void createsTasksInBulk() {
List<Opportunity> opps = new List<Opportunity>();
for (Integer i = 0; i < 200; i++) {
opps.add(new Opportunity(
Name = 'Bulk ' + i,
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30)
));
}
insert opps;
for (Opportunity opp : opps) opp.StageName = 'Closed Won';
Test.startTest();
update opps;
Test.stopTest();
System.assertEquals(
200,
[SELECT COUNT() FROM Task WHERE WhatId IN :opps]
);
}
}Recursion, limits, and asynchronous work
A static set can prevent a handler from processing the same record twice in one transaction.
private static Set<Id> processedIds = new Set<Id>();Use Limits.getQueries() and Limits.getDmlStatements() to measure consumption while debugging. If work remains too large, enqueue a Queueable job after the transaction.
public class RebuildQueueable implements Queueable {
private Set<Id> recordIds;
public RebuildQueueable(Set<Id> recordIds) {
this.recordIds = recordIds;
}
public void execute(QueueableContext context) {
// Query and process recordIds here.
}
}Exercise
Why should a trigger compare Trigger.new with Trigger.oldMap instead of creating work for every updated record?
Show answer
The comparison limits work to records whose relevant field actually changed, avoiding duplicate tasks and unnecessary limit consumption.