1

I want to do something dynamic with an Apex method. I have some custom metadata records that contain an object and field definition. I want to inject the field value from the object into a custom formula (the formula would be stored on the custom metadata record as well, as text) at run-time.

The goal is to allow the custom metadata record to be as configurable as possible without requiring changes to the Apex implementation.

The formula body would look something like this: YEAR({!field-value}) < {!custom-metadata date field} and the merge fields would be injected in the Apex method before evaluating the formula as a whole.

psuedo-code:

if field value is not null and a date:
  put merge values into formula
  evaluate formula

  if formula is TRUE:
    do foo()

Is it possible to do anything like this in Apex?

5
  • 1
    There are tricks to evaluate Strings in Apex, but that has security implications. Why don't you do the other way around? Create a formula field that depends on custom metadata records and configure the custom metadata records when needed?help.salesforce.com/…
    – Alba Rivas
    Jan 29 at 16:29
  • The problem I run into with formulas is that I can't create one on a custom metadata record. So I would need to place formulas on any and all objects that this formula would need to be evaluated on and that would defeat the purpose of using custom metadata with object and field definition references in the first place.
    – nbrown
    Jan 29 at 16:32
  • I think you are trying to rewrite SF a little bit :) So you want something that is set declaratively and can be used for every object and also in apex, that is the definition of a formula field. Jan 29 at 16:42
  • 3
    Then there's no native way of doing that, you'll have to do your own parsing. Some things that people have created are iandrosov.github.io/APEX-Expression-Eval or salesforce.stackexchange.com/questions/7792/…
    – Alba Rivas
    Jan 29 at 16:42
  • Have you tried this? developer.salesforce.com/docs/atlas.en-us.apexcode.meta/… If you define the formula as Alba mentioned, this could do the trick. Jan 29 at 23:22
0

Based on the feedback received in the comments and finding this Salesforce Idea: Evaluate Dynamic Formula with Apex, I've concluded what I want to do is not possible in Apex. There seems to be some libraries and examples of building custom interpreters/expression evaluators out there, however.

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.