Sub topic 1
A Save Is One Transaction
Prerequisites
You should know basic Apex syntax, Salesforce objects and fields, DML operations such as insert and update, and the purpose of validation rules and Flow.
One Save, One Transaction
A Salesforce save runs as one transaction. A transaction is a group of database work that either succeeds together or fails together. Salesforce processes the record through several stages before committing the change.
For example, an insert can run system validation, before-save Flow, a before trigger, and custom validation. If any stage produces an error, Salesforce rolls back the transaction. The new record is not committed.
Loading and Applying Values
Salesforce first loads the existing record when the operation is an update. It then applies the values supplied by the user, API request, import, or Apex code.
For an insert, there is no existing database record. Salesforce creates an in-memory version containing the incoming values. This version is the record that early automation can inspect and change.
System Validation Comes First
Salesforce performs system validation before running your before triggers. This includes checks such as field types, required fields, and valid formats. Salesforce also checks whether the user can perform the operation.
A failure at this stage stops the save. Later automation does not run for that record.
Before-Save Flows Run First
A before-save record-triggered Flow runs before an Apex before trigger. It can update fields on the record currently being saved without performing a separate database operation.
Use this Flow type for simple field updates that do not require related-record actions.
Before Triggers Change Incoming Records
A before trigger can change Trigger.new directly. Salesforce saves those changed values later, so no update statement is needed.
trigger AccountDefaults on Account (before insert, before update) {
for (Account accountRecord : Trigger.new) {
if (accountRecord.Description == null) {
accountRecord.Description = 'Default description';
}
}
}During before insert, the record does not yet have its database Id. Also, before-trigger logic should process every record in Trigger.new, because one transaction can contain many records.
Custom Validation Runs After Before Automation
After before-save Flow and before-trigger changes, Salesforce evaluates custom validation rules. This means a before trigger can populate a field that a validation rule then checks.
If the final values violate a validation rule, Salesforce reports the error and rolls back the entire transaction.
Exercise
An Account has a blank Description. A before trigger sets Description to "Default description." A validation rule requires Description to be populated. Does the validation rule see the new value?
Show answer
Yes. Custom validation runs after before-save Flow and before-trigger changes, so it sees "Default description."