Skip to main content
New tool CRON Expression Builder — preview next run times before you schedule Apex. Open the builder →
Diagram illustrating how Apex Dynamic Formulas execute logic directly within Salesforce Apex code execution.
Apex

Evaluate Dynamic Formulas in Apex - Spring '25 GA

Stop cluttering your schema with technical formula fields just so code can read them. Dynamic Formulas in Apex run formula logic straight from your triggers and classes, so admins can change the rules without waiting on a deployment.

The short answer

Dynamic Formulas in Apex let you evaluate a formula string at runtime against a record using the FormulaEval namespace. The business logic then lives in metadata instead of in extra custom fields or a hand-written formula parser.

Key takeaways Build formula instances with Formula.builder(), passing the target object type, return type, and formula string. Call getReferencedFields() on the formula instance so your SOQL queries only the fields the formula actually reads. Keep formula strings in Custom Metadata or Custom Settings so admins can change business logic without a deployment. Wrap every evaluation in try-catch, because a syntax error or a missing field fails at runtime.

Have you ever created a "technical" formula field just so you could pull a value into a trigger or a flow? It works, but it clutters the schema and makes maintenance miserable. The Spring '25 release makes Dynamic Formulas in Apex generally available, so that workaround is finally optional.

Say you have a rule engine or a pricing tool, and you want admins to tweak the logic without asking a developer for a deployment. Until now that meant writing a messy parser or leaning on those hidden fields. With the FormulaEval namespace you can run formula strings directly in your code.

Why dynamic formulas in Apex are worth your time

In my experience the best Salesforce setups are the ones where developers build the engine and admins supply the fuel. Dynamic formulas let you park the formula logic in Custom Metadata or Custom Settings. When the business changes a discount rule, an admin updates a text field and your Apex picks it up instantly.

There is a query benefit as well. The formula builder tells you which fields the formula needs before you run it, so you are not querying every field on an object on the off chance the formula wants one. If you are weighing Apex vs Flow for complex logic, that may push you toward code when the rules have to stay configurable and still run fast.

An Apex snippet in a code editor using the Formula builder pattern to evaluate a formula at runtime.

An Apex snippet using the Formula builder pattern to evaluate a formula at runtime.

How to implement dynamic formulas in Apex

The setup is straightforward. You use a builder pattern to define the formula, tell it which object type you are working with, and declare the result you expect back, such as a String, Boolean, or Number.

This is how I've been setting it up on my own projects. The method takes a formula string and a record ID, works out which fields to query, and evaluates the result.

@AuraEnabled
public static String evaluateRule(String formulaStr, String sobjectType, String returnTypeStr, Id recordId) {
    // Set up the return type
    FormulaEval.FormulaReturnType returnType = FormulaEval.FormulaReturnType.valueOf(returnTypeStr);

    // Build the formula instance
    FormulaEval.FormulaInstance instance = Formula.builder()
        .withType(Type.forName(sobjectType))
        .withReturnType(returnType)
        .withFormula(formulaStr)
        .build();

    // Get the fields we actually need to query
    List<String> fields = instance.getReferencedFields();
    String query = 'SELECT ' + String.join(fields, ',') + ' FROM ' + sobjectType + ' WHERE Id = :recordId LIMIT 1';
    
    SObject record = Database.query(query);
    
    // Run the formula against the record
    Object result = instance.evaluate(record);
    return String.valueOf(result);
}

One thing that trips people up is the return type. Make sure your Apex code and your formula string are in sync. If your formula returns a Boolean but your code expects a Decimal, you're going to have a bad time.

Practical tips

I have seen teams over-engineer this. Keep it simple and start with getReferencedFields(), which is the most overlooked part of the feature. Hard-code your queries and you throw away half the benefit. Let the formula tell you what it needs.

Then there is error handling. A formula fails if the syntax is wrong or a field is missing, so always wrap the evaluation in a try-catch. A typo in a Custom Metadata record should not take down an Apex trigger or a page.

Key takeaways

  • Dynamic formulas in Apex evaluate logic at runtime without extra fields.
  • Use Formula.builder() to define the object type and return type.
  • Always call getReferencedFields() to keep the SOQL query tight.
  • It suits rule engines, dynamic pricing, and custom validation tools.
  • Handle errors so an admin's mistake does not break the system.

Wrapping up

This one has been a long time coming. Most teams I work with are bogged down by "formula bloat," and this is a clean way out of it. The logic sits in a configuration layer where it belongs, and the Apex stays short and reusable.

If you build tools that admins have to manage themselves, dynamic formulas are worth an afternoon of your time. Both sides benefit: the developer stops shipping schema changes, and the business user stops waiting on a release.

Frequently asked questions

How do you evaluate dynamic formulas in Apex?

Build a formula instance with Formula.builder(), passing the SObject type, the return type, and the formula string, then call evaluate() with the record.

How do you know which fields to query for a dynamic formula in Apex?

Call getReferencedFields() on the FormulaInstance. It returns the fields the formula references, which is exactly the list your SOQL query needs.

Where should dynamic formula expressions be stored in Salesforce?

Keep them in Custom Metadata types or Custom Settings. Admins can then change the rules without a developer deployment.

Newsletter

One email every Tuesday

New guides, tool updates, and the release-note changes that break things.

No spam. Unsubscribe in one click.

Comments

Loading comments...

Leave a Comment