IntermediateLesson 19 of 37
Apex triggers
Code that runs when records change.
apex
trigger OpportunityTrigger on Opportunity (before insert, before update, after update) {
if (Trigger.isBefore) {
for (Opportunity o : Trigger.new) {
if (o.Amount != null && o.Amount < 0) {
o.addError('Amount cannot be negative.');
}
}
}
}Context variables: Trigger.new, Trigger.old, Trigger.newMap, Trigger.oldMap, Trigger.isInsert/isUpdate/isBefore/isAfter. Before triggers modify the records being saved (no extra DML needed); after triggers act on related records and can read the record Id.
Triggers always receive batches (up to 200 records), so write for many records, never one.