Sub topic 5
Before-Save Flows: Updating the Triggering Record
This chapter covers the before-save optimization of a record-triggered flow, called Fast Field Updates. It assumes you know the Salesforce data model, can build basic flows in Flow Builder, and can write simple formulas. It also assumes you know what a database transaction is. You should already know how to choose an object and trigger event, and how entry conditions work.
What a before-save flow is
A before-save flow runs before Salesforce writes the triggering record to the database. The record is still in memory. Changing a field on it means the new value is saved as part of the original operation.
You pick this behavior with the Optimize the Flow for setting, by choosing Fast Field Updates. The setting is made when you create the flow, and you can't change it to or from Actions and Related Records afterward without rebuilding the flow.
Because the flow edits the record in memory, it needs no extra DML (a database write such as insert or update). Salesforce saves the record once, and that single save includes the flow's changes. This is why Salesforce documents before-save flows as much faster than after-save flows that update the same record. The speed gain matters most in bulk operations such as data loads.
Configuring the flow
A before-save flow starts with the same choices as any record-triggered flow.
- Choose the object, for example Opportunity.
- Choose the trigger: a record is created, updated, or created or updated. Before-save flows can't be triggered by deletion in the Fast Field Updates optimization, so use another approach for delete logic.
- Add entry conditions so the flow runs only when it should.
- Choose the run frequency for update triggers: every time the record meets the conditions, or only when it is updated to meet them.
- Select Fast Field Updates.
The following configuration sets a field on large deals.
Flow: Opportunity - Set Next Step (before-save)
Object: Opportunity
Trigger: A record is created or updated
Optimize for: Fast Field Updates
Entry condition: {!$Record.Amount} > 100000
Run: Only when a record is updated to meet the condition requirements
Assignment element
Variable: {!$Record.NextStep}
Operator: Equals
Value: Review large dealThe run setting "Only when a record is updated to meet the condition requirements" is important here. It means the flow runs when the record changes from not meeting the condition to meeting it, not on every later edit of a large deal. Without this setting, a user who edits NextStep by hand on a large deal would have the value overwritten at the next save.
Changing fields with Assignment
In a before-save flow you change the triggering record by assigning values to {!$Record} fields with an Assignment element.
- Set a field with
{!$Record.FieldName}as the variable, an operator such as Equals, and a value. - You can assign several fields in one Assignment element.
- You do not use an Update Records element for the triggering record. Update Records isn't available for
$Recordin a before-save flow. - Changes are kept when the flow finishes. You don't have to store
$Recordanywhere else.
$Record holds the values as the flow sees them at that point. Each Assignment changes it, and later elements see the changed values. $Record__Prior holds the values before the change and stays fixed. Use it with $Record to detect changes. This works on update triggers, and $Record__Prior is empty on creation.
Detecting a change
You can compare current and prior values in a Decision element. You can also put a formula in the entry condition, as in this condition for an Opportunity that has just moved to Closed Won:
AND(
ISCHANGED({!$Record.StageName}),
{!$Record.StageName} = "Closed Won"
)Use this formula with the entry condition type Formula Evaluates to True. Putting the test in the entry condition is cheaper than starting the flow and testing in a Decision. When the condition is false, the flow doesn't start.
What a before-save flow can and can't do
The Fast Field Updates optimization limits what the flow may contain. The restrictions follow from the timing. The record has no Id on create, and other records haven't been saved yet.
| Task | Before-save | Notes |
|---|---|---|
| Assign values to `$Record` fields | Yes | The main purpose |
| Read `$Record` and `$Record__Prior` | Yes | `$Record__Prior` applies to updates |
| Use Decision, Loop, Formula, and Assignment | Yes | Use these to compute values |
| Get Records on other objects | Yes | Reads count toward SOQL limits |
| Create, Update, or Delete other records | No | Use after-save |
| Use `{!$Record.Id}` on create | No | The Id doesn't exist yet |
| Call actions such as email or Apex | No | Use after-save |
| Launch subflows that change data | No | Use after-save |
| Use asynchronous or scheduled paths | No | Use after-save |
Flow Builder won't let you add the unavailable elements to a before-save flow.
The missing Id on create is the most common design problem. If you need to relate another record to the triggering record, a before-save flow can't do it, because there is no Id to put in a lookup field. An after-save flow can use {!$Record.Id}, as in this example:
Flow: Opportunity - Create Follow-up Task (after-save)
Object: Opportunity
Trigger: A record is created or updated
Optimize for: Actions and Related Records
Entry condition: {!$Record.StageName} = "Closed Won"
Run: Only when a record is updated to meet the condition requirements
Create Records element (object: Task)
Subject: Send welcome package
WhatId: {!$Record.Id}
OwnerId: {!$Record.OwnerId}Where it runs in the save
Before-save flows run early in the order of execution. Salesforce loads the record and applies the incoming values. It then runs before-save flows, and after that it runs the system validations, custom validation rules, and before Apex triggers. Exact placement relative to other logic belongs to a later chapter. For this chapter, remember three consequences.
- Your flow sees the values the user or API sent. It does not see the results of later steps, such as values that a before Apex trigger sets.
- Validation rules run after your flow. A value your flow assigns can cause a validation rule to fail, or can make a rule pass.
- Required-field and data-type checks still apply. If you assign text that doesn't fit a field, the save fails.
Before-save flows also share the transaction with Apex and other automation. They use the same governor limits for the transaction, including SOQL queries. A Get Records element counts as a query, so avoid putting one inside a Loop.
Bulk behavior
A before-save flow is bulkified by the platform. When a data load saves 200 records in one batch, Salesforce runs the flow's interview logic across the batch. Elements such as Get Records are combined where possible. You still need to avoid patterns that defeat this, mainly Get Records inside a Loop. Retrieve once before the loop and use a collection when several records are involved.
A before-save flow that changes only the triggering record uses no DML, so it won't consume DML statement or DML row limits. This is the main reason to choose it for simple field changes.
Common errors
- Trying to update
$Recordwith Update Records. In a before-save flow, use Assignment. An Update Records element would also be wrong in design, because it performs an extra write. - Overwriting user input. Entry conditions and the run frequency decide whether your flow replaces values the user typed. Test with a manual edit after the flow has run.
- Needing the Id on create. If a requirement says "create a related record when this one is created", it needs after-save.
- Expecting changes to be visible to a later after-save flow only. Changes made in a before-save flow are saved with the record, so after-save flows and later logic see them in
$Record. - Forgetting that before Apex triggers can overwrite your values. A trigger that runs after your flow can change the same field.
Testing a before-save flow
You can test with the debug tool in Flow Builder, which lets you supply a record and see the assignment results. You can also test with Apex. The following test assumes the flow above is active. It inserts a large Opportunity, then queries it to confirm the flow's assigned value was saved.
@IsTest
private class OpportunityFlowTest {
@IsTest
static void beforeSaveFlowSetsNextStep() {
Opportunity opp = new Opportunity(
Name = 'Large deal',
StageName = 'Prospecting',
CloseDate = Date.today().addDays(30),
Amount = 200000
);
insert opp;
Opportunity saved = [SELECT NextStep FROM Opportunity WHERE Id = :opp.Id];
Assert.areEqual('Review large deal', saved.NextStep);
}
}The test queries the record again because the in-memory opp variable in Apex doesn't show the flow's change. The database does.
Exercise
A requirement says: when an Account's Rating changes to Hot, set its Description field to "Priority account", and also create a Task for the owner linked to the Account. Which parts can a before-save flow handle, and which need after-save?
Show answer
The Description change can be done in a before-save flow with an Assignment on {!$Record.Description}, using an entry condition such as AND(ISCHANGED({!$Record.Rating}), {!$Record.Rating} = "Hot"). Creating the Task needs an after-save flow, because it creates another record and uses the Account's Id as WhatId. Both can be one after-save flow, but the Description change then uses an extra update, so splitting them is faster.
Exercise
Why does a before-save flow not need an Update Records element to save its changes to the triggering record?
Show answer
The flow runs before the record is written. Assignments change the record in memory, and Salesforce then saves the record once with those changes, so no extra DML is needed.