Refreshing Formula Fields Dynamically (without save)

Good news everybody!

This has just been added to the Winter '16 release. It can be used like this:

someSObject.recalculateFormulas();

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.

See https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_sobject.htm

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


Unfortunately not. Formula fields aren't stored in a Salesforce record, rather the formula definition is executed at the time that the record is queried from the database. So its the act of retrieval that populates the field based on the formula.

Another option is to save the record, query it from the database including the formula fields, capture the formula fields into controller properties or similar and then delete the record. Its clunky but it will allow you to get at the formula fields without leaving a half-populated record in the database.


As noted elsewhere, the sObject.recalculateFormulas() does exactly this; unfortunately, however, that feature currently has a bug that makes it much less useful than it could be.

There is a Known Issue regarding this bug, but essentially the problem is that if any non-updatable fields are in the SOQL query that the recalculateFormulas() will be referencing, it will fail. This includes built-in fields (IsDeleted, CreatedDate, etc.) and custom fields, as well as fields referenced from other sObjects in the SOQL query.