Imagine a scenario where you need to check complex conditions on an SObject record and don’t want to or can’t create a formula field on the object? Dynamic formula evaluation solves your problem. This capability was added in Summer 24. Let’s see an example:
FormulaEval.FormulaInstance isPrimeCustomer = Formula.builder() .withType(Account.SObjectType) .withReturnType(FormulaEval.FormulaReturnType.BOOLEAN) .withFormula('AnnualRevenue > 30000 AND ISPICKVAL(Industry, "retail") AND Prime_Customer__c = TRUE'); Account acc1 = new Account( Name = 'Test Dynamic Formula Account', AnnualRevenue = 40000, Industry = 'Retail', Prime_Customer__c = true ); isPrimeCustomer.evaluate(acc1); // returns TRUE Account acc2 = new Account( Name = 'Test Dynamic Formula Account 2', AnnualRevenue = 30000, Industry = 'Information Technology', Prime_Customer__c = false ); isPrimeCustomer.evaluate(acc2); // returns FALSE Account acc3 = new Account( Name = 'Test Dynamic Formula Account 3', AnnualRevenue = 10001, Industry = 'Chemical', Prime_Customer__c = true ); isPrimeCustomer.evaluate(acc2); // returns FALSE
Also another example with a wrapper class:
global class Car { global Double lengthMeters; global Integer numOfSeats; global String name; } Car myBMW = new Car(); myBMW.lengthMeters = 5.2; myBMW.numOfSeats = 4; myBMW.name = 'BMW M4'; FormulaEval.FormulaInstance isLongCar = FormulaEval.FormulaBuilder.builder() .withReturnType(FormulaEval.FormulaReturnType.STRING) .withType(Car.class) .withFormula('IF(lengthMeters > 5, "Long", "Short")') .build(); isLongCar.evaluate(myBMW); // Returns "Long" FormulaEval.FormulaInstance isPrimeCustomer = Formula.builder() .withType(Account.SObjectType) .withReturnType(FormulaEval.FormulaReturnType.BOOLEAN) .withFormula('AnnualRevenue > 15000 AND ISPICKVAL(Industry, "retail") AND Prime_Customer__c = TRUE');
As you can see, you now can evaluate dynamic formulas in Apex. One thing I can think of is freeing up some fields on objects with a large number of fields by moving some formula fields over to dynamic formulas within Apex where it makes sense to do so. Also one can fully customize a formula using Apex variables and custom settings. Awesome stuff.