The Dynamic Formula brings enhanced capabilities for evaluating user-defined formulas for Apex objects and sObjects.
With the new ‘FormulaEval’ namespace, you can now optimise database CPU demands and avoid static expressions when evaluating formula expressions.
Note : To leverage this feature, ensure that the FormulaEvalInApex feature is enabled in your scratch orgs.Without the feature enabled, Apex code utilising this feature can be compiled but not executed.
Creating a formula instance is made easy with the FormulaBuilder class.
Simply call the static method builder() with the formula text, return type, and context object.
Validate the formula instance by using the build() method, which may trigger the FormulaValidationException exception if the validation fails.
Once your formula instance is validated, you can calculate the formula expression and retrieve the result using the evaluate() method in the FormulaInstance class.
If an error occurs during evaluation, the method will trigger the FormulaEvaluationException exception.
Ex : The usage of the build() and evaluate() methods
global class MotorYacht {
global Integer lengthInYards;
global Integer numOfGuestCabins;
global String name;
global Account owner;
}
MotorYacht aBoat = new MotorYacht();
aBoat.lengthInYards = 52;
aBoat.numOfGuestCabins = 4;
aBoat.name = 'Go Boat';
// Example 1: Evaluate 'isItSuper' formula instance
FormulaEval.FormulaInstance isItSuper = FormulaEval.FormulaBuilder.builder()
.withReturnType(FormulaEval.FormulaReturnType.STRING)
.withType(MotorYacht.class)
.withFormula('IF(lengthInYards < 100, "Not Super", "Super")')
.build();
isItSuper.evaluate(aBoat); //=> "Not Super"
// Example 2: Evaluate 'ownerDetails' formula instance
aBoat.owner = new Account(Name='Acme Watercraft', Site='New York');
FormulaEval.FormulaInstance ownerDetails = FormulaEval.FormulaBuilder.builder()
.withReturnType(FormulaEval.FormulaReturnType.STRING)
.withType(MotorYacht.class)
.withFormula(‘owner.Name & " (" & owner.Site & ")"')
.build();
ownerDetails.evaluate(aBoat); //=> "Acme Watercraft (New York)"