18

Is there a way to add an error on a dynamically referenced field? Let's take this simple example:

opp.get('Name').addError('Invalid name');

This is not working, I'm looking for a similar minded way.

Thanks

2 Answers 2

20

Sadly I have to report the answer to your question is no. For me this is the final peace of Dynamic Apex to complete the ability to build truly 100% dynamic Apex libraries and solutions.

I've searched for workarounds and can find none, the addError methods on SObject use a highly specialised way to reference the field which is to hard code the field reference ahead of the method. Here is the Idea Exchange idea to upvote!

This method is highly specialized because the field identifier is not actually the invoking object—the sObject record is the invoker. The field is simply used to identify the field that should be used to display the error.

5
  • 2
    So I guess I will not be able to create dreamlike validation utility that I was wishing for... for now. Thanks Andrew for confirming my thoughts.
    – jpmonette
    Jun 13, 2013 at 14:28
  • Yes sadly not for the moment.... Jun 13, 2013 at 21:59
  • 3
    Kind of hard to believe this still has not become reality.
    – Adrian Larson
    May 29, 2015 at 17:22
  • And now with the advent of Lightning UI, we may never see this... Jul 8, 2016 at 0:36
  • Even with Lightning it still makes sense to have the ability to add errors to dynamically selected fields. It is quite a bizarre state of the API to only allow this at the SObject, rather than field, level.
    – Phil W
    May 15, 2019 at 19:10
1

Winter '21 Update (v50.0)

Salesforce have finally added the ability to add an error to a field dynamically

We can now do the following:

String myFieldString = 'Name';
opp.addError(myFieldString, 'Invalid name');

Or, add as a Schema.SObjectField reference

Schema.SObjectField myField = Opportunity.Name;
opp.addError(myField, 'Invalid name');
1
  • Thank you for this! Worked like a charm.
    – unhinged
    May 4, 2022 at 1:37

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.