3

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.

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?) Sep 18 '15 at 18:44
  • 1
    I've run some testcode and indeed, there is no DML statements, so you should be good to do callouts. Sep 21 '15 at 7:40

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.