7

I know I can add an error to a field as follows:

Account someAccount = [select id, name from Account limit 1];
someAccount.name.addError('Bad Name');

How can I do that if the field name is only available as a String?

Account someAccount = [select id, name from Account limit 1];
String someField = 'name';
// if I could only do something like the below
someAccount.addError(someField, 'Bad Name');
0
15

You could vote for this Provide an additional addError method on SObject that accepts a field name idea, but as it has got nowhere in the last 5 years there is no reason to expect any progress in the next 5 years.

6
  • 2
    +1 for mordancy; I voted for this as I would have found this useful
    – cropredy
    Jun 9 '15 at 21:16
  • Documentation for addError notes that "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." In other words, it's actually syntactic sugar for what would be a two or three parameter function (two if you don't use the optional escape boolean).
    – sfdcfox
    Jun 9 '15 at 21:20
  • 2
    @crop1645 I had to Google "mordancy" but yes an appropriate word. Seems like a method that should be there to allow dynamic coding to be functionally equivalent to static coding.
    – Keith C
    Jun 9 '15 at 21:22
  • Agreed, nice answer. This is clearly a duplicate question though.
    – Adrian Larson
    Jun 9 '15 at 21:33
  • 1
    For anyone looking 6 years later, this was implemented in Winter 2021. Example: String fName = 'Status'; object.addError(fName,'You must provide a ' + fName); May 28 at 13:14

Not the answer you're looking for? Browse other questions tagged or ask your own question.