# Force Formula Recalculation in Apex

Here’s a quick tip on what you can do if you need a calculated value in Apex when you are creating a new record or modifying a record.

Consider this situation -

• You are creating a contact in Apex
• You provided all the necessary fields - `Name`, `Title`, `Birthdate`
• You have logic driven by the age of the contact. You decide to use `Age__c`, a field that you had created for the purpose

The script is simple enough -

``````
Contact c = new Contact();
c.Birthdate = date.valueof('2001-01-01');
System.debug('Age: ' + c.Age__c);

``````

.. where `Age__c` is a custom field that calculates age in months depending on the birth date.

To no one’s surprise - the calculated value from the debug statement will be `null`. Salesforce will not apply calculations at this stage (assuming this code is in a class, triggers are a different story).

Before you go about replicating the complex age calculation logic in Apex, know this - it is simple to retrieve calculations at any time in Apex. All it needs is a couple of new lines of code that uses the method `Formula.recalculateFormulas()`.

``````
Contact c = new Contact();
c.Birthdate = date.valueof('2001-01-01');
System.debug('Age: ' + c.Age__c);
// null

List<Contact> contactList = new List<Contact>{c};
List<FormulaRecalcResult> calcContacts = Formula.recalculateFormulas(contactList);
System.debug('Age (recalc): ' + contactList.get('Age__c'));
// the correct age!

``````

This method is super useful when you need to drive Apex logic based on formula fields.

Also, here’s another quick tip. If the formula field is complex, has multiple moving parts (e.g. a series of formulae referencing one another), and, in general, is taking you multiple iterations to get right - it may be just easier to evaluate the formula in Apex test classes and write automated tests to compare against the expected results.

Last updated:
Categories: Apex
Tags: apex