Sub topic 8
Changing Field Values in Before Triggers
This chapter assumes you can read basic Apex (loops, collections, maps), know what a record Id is, and have seen DML statements and governor limits. You should also know the seven trigger events and the difference between before and after timing from earlier chapters.
By the end you will know why a before trigger can change records without any DML, which events allow it, and which mistakes cause errors or silent failures.
Why before triggers can edit records directly
In a before trigger, the records in Trigger.new are in memory and have not yet been written to the database. Salesforce runs your trigger, then saves whatever values the records hold at that point. If you assign a new value to a field on a record in Trigger.new, that value is what gets saved.
This has three practical results:
- You do not call
insertorupdateon the records you are changing. - The change costs no extra DML statement and no extra DML rows against governor limits.
- The change does not fire the same trigger again, because no new save operation starts.
trigger AccountTrigger on Account (before insert, before update) {
for (Account a : Trigger.new) {
if (String.isBlank(a.Description)) {
a.Description = 'Set by AccountTrigger';
}
}
}The loop variable a refers to the same object that is in Trigger.new. Assigning to a.Description changes that record. No copy is made, so nothing needs to be written back.
Which events allow edits
Only two before events let you change the record being saved.
| Event | Edit `Trigger.new` fields? | Notes |
|---|---|---|
| before insert | Yes | Record has no Id yet. |
| before update | Yes | `Trigger.old` and `Trigger.oldMap` show prior values. |
| before delete | No | There is no `Trigger.new`. Records are in `Trigger.old`, which is read-only. |
| after insert | No | Records are read-only. |
| after update | No | Records are read-only. |
| after delete | No | Records are read-only. |
| after undelete | No | Records are read-only. |
Before delete is a before event, but it has nothing to edit, because the record is going away. Use it to block the delete, not to change values.
The record Id is not available on insert
In a before insert trigger, Trigger.new records have a null Id. The database has not assigned one yet. Two consequences follow.
Trigger.newMapis null in before insert, because a map keyed by Id cannot be built from null Ids.- You cannot use
a.Idas a relationship key, for example asWhatIdon a Task. That work belongs in an after insert trigger.
In before update, Trigger.new records already have Ids, so Trigger.newMap and Trigger.oldMap both exist.
Editing only when something changed
A common requirement is to act on a transition, not on every save. In before update, compare the new value to the old one. Trigger.oldMap, keyed by record Id, returns the prior version of each record.
trigger OpportunityTrigger on Opportunity (before update) {
for (Opportunity opp : Trigger.new) {
Opportunity oldOpp = Trigger.oldMap.get(opp.Id);
if (opp.StageName != oldOpp.StageName && opp.StageName == 'Closed Won') {
opp.CloseDate = Date.today();
}
}
}Without the stage comparison, this trigger would reset CloseDate on every later edit to a closed opportunity. Comparing old and new restricts the edit to the one save where the stage moved to Closed Won.
Do not use Trigger.oldMap in before insert. It is null there, and calling get on it throws a System.NullPointerException. If one trigger handles both insert and update, check the context first.
trigger LeadDefaults on Lead (before insert, before update) {
for (Lead l : Trigger.new) {
if (Trigger.isInsert) {
if (l.LeadSource == null) {
l.LeadSource = 'Other';
}
} else if (Trigger.isUpdate) {
Lead oldLead = Trigger.oldMap.get(l.Id);
if (l.Company != oldLead.Company) {
l.Description = 'Company changed from ' + oldLead.Company;
}
}
}
}Common uses
Before triggers fit work that depends only on the record being saved, or on a small amount of related data.
- Setting defaults when a field is blank.
- Normalizing values, such as trimming whitespace or changing the case of a code.
- Calculating a field from other fields on the same record.
- Stamping a date when a status changes.
- Copying a value from a parent record that you queried once for the whole batch.
If the requirement is a simple calculation on the same record, a formula field or a record-triggered flow might be the better tool. A trigger is the right choice when the logic is complex, needs to be tested as code, or must run in a defined position relative to other Apex.
Staying bulk-safe while editing
A trigger receives up to 200 records per batch. Editing fields in a loop is fine, because it costs no DML. The danger is in what else the loop does. A SOQL query inside the loop runs once per record and exceeds the limit of 100 synchronous queries when the batch is large.
To copy a value from a parent record, collect the parent Ids first, query once, and look values up from a map.
trigger ContactRegion on Contact (before insert, before update) {
Set<Id> accountIds = new Set<Id>();
for (Contact c : Trigger.new) {
if (c.AccountId != null) {
accountIds.add(c.AccountId);
}
}
Map<Id, Account> accounts = new Map<Id, Account>(
[SELECT Id, BillingCountry FROM Account WHERE Id IN :accountIds]
);
for (Contact c : Trigger.new) {
Account parent = accounts.get(c.AccountId);
if (parent != null && String.isBlank(c.MailingCountry)) {
c.MailingCountry = parent.BillingCountry;
}
}
}The pattern has three steps: gather keys, run one query, then edit in a second loop. When c.AccountId is null, accounts.get(null) returns null, so the null check on parent covers contacts with no account.
Mistakes and how they show up
Calling DML on Trigger.new in a before trigger
trigger BadBefore on Account (before update) {
update Trigger.new; // Do not do this.
}Salesforce rejects this. In a before update trigger, an explicit update of the same records causes a runtime error, and in before insert the records have no Ids to update. The edit alone already saves the data, so the DML adds nothing.
Editing in an after trigger
In an after trigger the records in Trigger.new are read-only. Assigning a field value throws System.FinalException: Record is read-only. If you need to change the same record after the save, query it again or build a new sObject with the same Id, and update that. Be aware that this fires triggers again, so plan recursion control. When the change could have been made in a before trigger, move it there. It is cheaper and avoids the second save.
Editing a record from a different list
Changes persist only on the objects that Salesforce is saving. If you query the same record into a new variable and edit that variable, the change is not saved by the original operation.
trigger WrongObject on Account (before update) {
for (Account a : Trigger.new) {
Account copy = [SELECT Id, Description FROM Account WHERE Id = :a.Id];
copy.Description = 'Lost'; // Not part of the save, so it has no effect.
}
}This is also a query inside a loop. Edit the record from Trigger.new itself.
Assuming your edit is final
Your before trigger is not the last thing that can change a record. Other before triggers on the same object run in no guaranteed order. Later steps, such as workflow field updates and flows, can change values after your trigger finishes. Write triggers so they do not depend on running before or after another trigger on the same object. Chapter 16 covers the full order of execution.
Reading a changed value as if it were the original
Inside the trigger, Trigger.new holds the values after your own edits. Trigger.old and Trigger.oldMap hold the stored values from before the save. If you edit a field and then compare it with the old value, the comparison reflects your edit, not what the user typed.
Summary of rules
- Edit
Trigger.newrecords directly in before insert and before update. - Do not issue DML on those records in the same trigger.
- Check
Trigger.isInsertorTrigger.operationTypebefore readingTrigger.oldMap. - Move any SOQL out of the loop and read from a map.
- Treat
Trigger.newin after events as read-only.
Exercise
A before update trigger on Opportunity should set a custom field Last_Stage_Change__c to today's date, but only when StageName changes. A teammate wrote update Trigger.new; at the end of the loop to save the change. What is wrong with that line, and how should the trigger decide when to set the date?
Show answer
The line is unnecessary and causes an error. In a before trigger, values assigned to records in Trigger.new are saved automatically, and DML on those same records inside the trigger is rejected. Remove it. To limit the edit to real stage changes, get the old record with Trigger.oldMap.get(opp.Id) and set opp.Last_Stage_Change__c = Date.today(); only when opp.StageName != oldOpp.StageName.
Exercise
A trigger on Contact runs on before insert and before update. It uses Trigger.oldMap.get(c.Id).Email for every contact. It works on update but fails on insert. Why, and what is the fix?
Show answer
On before insert, Trigger.oldMap is null, so calling get on it throws a NullPointerException. Wrap the oldMap access in a check such as if (Trigger.isUpdate), or switch on Trigger.operationType so the old values are read only for BEFORE_UPDATE.