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
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It only takes a minute to sign up.
Sign up to join this communitySadly 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.
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');