Presentations About Resources

Salesforce, Python, SQL, & other ways to put your data where you need it -- a bilingual blog in English & French

Recalculating Salesforce Formula Fields in Apex

10 Sep 2019 🔖 salesforce apex tips tutorials
💬 EN ( Lire cet article en français )

Salesforce Winter ‘20 has a new Formula class in Apex – check out what it can do.

James Hou pointed out, quoted in Windyo’s excellent abridged Winter ‘20 release notes on Reddit :

Formulas recalculation in APEX: That is HUGE.

You can calculate formulas without a DML, in batch.

Let that sink in…. you can basically have formulas lift heavy calculations and do it in an Apex class without saving.

And it’s true!

Here’s an example in the form of a unit test:

public class ATest {
	static testMethod void runTest() {
		ParentObject__c parent = new ParentObject__c(
			Name = 'Parent',
			Code__c = 'ABAB'
		INSERT parent;
		ChildObject__c child = new ChildObject__c(
			Name = 'Child',
			Code__c = 'XYXY',
			Parent__c = parent.Id
		System.assertEquals(NULL, child.Concatenated_Formula_Field__c);
		Formula.recalculateFormulas(new List<ChildObject__c>{child});
		System.assertEquals('ABAB|XYXY', child.Concatenated_Formula_Field__c);

Note that the object named child does not exist yet in the database – it’s an in-memory SObject only.

I have not yet saved it to the database with an INSERT command.

And yet, after running Formula.recalculateFormulas(), the value of the field Concatenated_Formula_Field__c is ABAB|XYXY.

Notez: In this case, the formula itself is:

& "|" &
--- ---