Sub topic 1
What an Apex trigger is and when it runs
Prerequisites
You should know basic Apex syntax, sObjects, SOQL, DML, and the Salesforce data model. You should also know that records can be inserted, updated, deleted, or undeleted.
A trigger is an automatic entry point
An Apex trigger is code that Salesforce runs automatically when records change. A trigger is attached to one sObject and one or more database events, such as before insert or after update.
For example:
trigger AccountTrigger on Account (before insert, before update) {
for (Account accountRecord : Trigger.new) {
if (String.isBlank(accountRecord.Description)) {
accountRecord.Description = 'Created by automation';
}
}
}This trigger changes fields before Salesforce saves each Account. A trigger does not run because a user clicked a particular button. It runs because a matching database event occurred. The event might come from the user interface, an integration, a data load, or another Apex transaction.
Reading trigger context
The trigger context provides the records and information about the current event.
Trigger.newcontains the new versions of records.Trigger.oldcontains the previous versions during update or delete events.Trigger.newMapandTrigger.oldMapmap record IDs to records when IDs are available.Trigger.isInsert,Trigger.isUpdate, and similar flags identify the event.Trigger.isBeforeandTrigger.isAfteridentify the execution phase.
On insert, Trigger.oldMap is null because no previous record exists. On delete, use Trigger.old, because there is no new saved version.
Choosing before or after
Use a before trigger when changing fields on the records being saved. The changes are written as part of the original save, so you do not perform another update.
Use an after trigger when you need saved record IDs, system-generated values, or related-record DML. Records in an after context are read-only.
Governor limits and batches
Governor limits cap shared resources in one transaction. For example, synchronous Apex normally allows 100 SOQL queries. A data load can invoke a trigger with up to 200 records, and every record shares that limit.
Therefore, this pattern is unsafe:
for (Account accountRecord : Trigger.new) {
List<Contact> contacts = [
SELECT Id FROM Contact WHERE AccountId = :accountRecord.Id
];
}The loop can execute too many queries. Bulkified code treats Trigger.new as a collection and queries once for the whole batch.
Exercise
Which context should you use to set a field on the record being inserted?
Show answer
Use a before trigger, because the record can be changed without another DML update.