Sub topic 2
Loading the record and applying new values
This chapter assumes you can write a basic Apex trigger and know what insert and update DML do. It covers the first two steps of the order of execution, which happen before any validation or trigger runs.
Step 1: Load the original record
On an update, Salesforce first loads the existing record from the database. This copy holds the values as they were before your change. On an insert there is no stored record, so Salesforce starts with a new, empty record that has default values.
Step 2: Overwrite with the new values
Salesforce then takes the field values from the request and writes them over the loaded record. The request can come from the user interface, an API call, or Apex DML.
Only the fields in the request are overwritten. Every other field keeps its stored value. The result is a complete record that combines old and new data.
What triggers see
The result of these steps is what your trigger receives.
Trigger.newholds the merged record: the original values plus the new ones.Trigger.oldholds the original record as loaded in step 1.Trigger.oldMapholds the same original records, keyed by Id.
trigger AccountChangeDemo on Account (before update) {
for (Account a : Trigger.new) {
Account original = Trigger.oldMap.get(a.Id);
if (a.Phone != original.Phone) {
System.debug('Phone changed from ' + original.Phone + ' to ' + a.Phone);
}
}
}Now suppose an Apex update sends only a new name:
Account acc = new Account(Id = '001000000000001AAA', Name = 'Acme Global');
update acc;The record in Trigger.new still has its stored Phone, Industry, and every other field. Only Name differs from Trigger.old. This is why comparing Trigger.new with Trigger.oldMap is the standard way to detect a real change.
Common errors
- Assuming an empty field in the request means "clear it." A field you leave out keeps its old value. Only a field you explicitly set to null is cleared.
- Treating every update as a change. A save can run with no actual difference in a field. Compare old and new values before acting.
- Reading
Trigger.oldon insert. It is null, as noted above.
Exercise
An Apex update sends an Account with only the Id and Name set. The stored record has Phone = '555-0100'. What is Trigger.new[0].Phone in a before update trigger, and why?
Show answer
It is '555-0100'. Salesforce loads the original record first, then overwrites only the fields in the request. Phone was not in the request, so it keeps its stored value.