4

My objective: I want to be able to programatically evaluate a formula expression in the same manner as SFDC does for formula fields. I wish to do this so that I can have formula parsing which is in line with SFDC standards.

Example Scenario I have an object type MyObject__c with field MyFormula__c. This field is a String (Text).

For one instance of this object, MyFormula__c = "1+1" (or a more complex scenario - "TotalCost__c - Discount__c")

I want a way that I can take this stored value of a formula, and that I can calculate it wrt my current instance of the object type. I want to do this at Apex runtime, not at SOQL-data retrieval. Can anyone help me with this? Is this even possible?

I've found a number of ways to tackle similar cases: Get a formula field's description at runtime, eval() via ToolingAPI / exception. etc...

I've found options like... Create an instance of the object in memory. Save it, then query it right back to get its calculated data. But nothing for calculating in Apex runtime.

Note I can create my own formula parser. I prefer not to in order to maintain standards and streamline UX / etc.

2 Answers 2

7

You are so lucky. This has just been added to the Winter '16 release.

someSObject.recalculateFormulas();

Will do the trick.

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 http://releasenotes.docs.salesforce.com/en-us/winter16/release-notes/rn_apex_new_classes_methods.htm

2
  • Oh wow! This is amazing news! ..... I'm certain I read "without a database commit" somewhere. But I can't find it now. Can you confirm that there will be no database commit "under the hood"? (ie. I will be able to make a callout after using this?) Commented Sep 18, 2015 at 18:44
  • 1
    I've run some testcode and indeed, there is no DML statements, so you should be good to do callouts. Commented Sep 21, 2015 at 7:40
1

Posting this in my current role as the Salesforce Product Manager for Apex.

We have a current Beta for dynamic evaluation of formulas in Apex. See Evaluate Dynamic Formula with Apex | IdeaExchange for the latest details.

The general concept is that you can create a FormulaBuilder in Apex and dynamically build up a FormulaInstance. For instance, you would define the type it is evaluating against, the return type, and the formula itself as a string. Once you have the FormulaInstance you can evaluate it against in memory objects of the correct type.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .