Sudipta Deb

Sudipta Deb

Founder of Technical Potpourri, Co-Founder of Shrey Tech, Enterprise Cloud Architect

What is Evaluate Dynamic Formulas in Apex?

“Evaluate Dynamic Formulas in Apex” is a new feature in Salesforce scheduled for release with Summer ’24 (currently in beta). It allows developers to programmatically evaluate Salesforce formulas within Apex code. This means you can write code that takes a formula as input (as a string) and evaluates it based on the context you provide, similar to how formulas are evaluated in fields or rules within Salesforce.

Here are some potential benefits of this feature:

  • Real-time Calculations: Eliminate the need to store pre-calculated formula results in fields, improving efficiency.
  • Increased Flexibility: Create more dynamic logic in automations, validations, and workflows by evaluating formulas at runtime.
  • Enhanced User Experience: Build custom formula editors that leverage the power of the Salesforce formula engine.

Watch The Video Or Read The Article (Or Do Both smile)

Example Code:

Below is one sample code using Apex Cursors

public with sharing class DynamicFormula {
 public void opportunityChecker(String opportunityId){
 Opportunity singleOpp = [Select Id, Amount, ExpectedRevenue, Probability from Opportunity where Id =: opportunityId LIMIT 1];
 String formulaExpresssion = '(Amount > 10000 && Probability > 50) || (ExpectedRevenue > 20000 && Probability > 80)';
 FormulaEval.FormulaBuilder likelyConvertOpportunity = Formula.builder()
 .withType(Opportunity.SObjectType)
 .withReturnType(FormulaEval.FormulaReturnType.BOOLEAN)
 .withFormula(formulaExpresssion); 
 FormulaEval.FormulaInstance instance=likelyConvertOpportunity.build();
 Boolean formulaOutcome = (Boolean)instance.evaluate(singleOpp);
 System.Debug('Formula Result: ' + formulaOutcome);
 }
}

Explanation Of The Code

To create an instance of the formula, I have called the static method builder() in the FormulaBuilder class and passed in the context object, return type, and formula text in the code above. The formula instance was validated by calling the build() function. In the event that the validation fails, the build() method generates the FormulaValidationException exception.

To calculate the formula expression and return the result, I have used the evaluate() function of the FormulaInstance class. If the evaluation yields an error, the method generates the FormulaEvaluationException exception.

Disclaimer

This article is not endorsed by Salesforce, Google, or any other company in any way. I shared my knowledge on this topic in this blog post. Please always refer to Official Documentation for the latest information.

0 Comments

Submit a Comment

Your email address will not be published. Required fields are marked *