Skip to content

Recalculate Formula Fields Dynamically (without save)

From the Documentation:

Recalculates all formula fields on an sObject, and sets updated field values. Rather than inserting or updating objects each time you want to test changes to your formula logic, call this method and inspect your new field values. Then make further logic changes as needed.


Note that this method doesn’t recalculate cross-object formulas, only ‘local’ formula’s referring to the record itself!

Recalculate fields for a list of records
Account a = new Account();
a.Name = 'Salesforce';
a.BillingCity = 'San Francisco';
List<Account> accounts = new List<Account>{a};

List<FormulaRecalcResult> results = Formula.recalculateFormulas(accounts);
// Option 1
System.debug('New value: ' + accounts[0].get('My_Formula_Field__c'));
// Option 2
System.debug('New value: ' + results[0].getSObject().get(‘My_Formula_Field__c’));
recalculate formula just for a record