Apex AddError to SObject field

Jeff picture Jeff · Dec 9, 2012 · Viewed 9k times · Source

Has anyone found a way of adding a dynamic field level error to an sobject?

I would like to do something like

mySobjectRec.get('fieldname').addError('my error message');

I realise that mySobjectRec.fieldname__c.addError('my error message') works.

Answer

Egor Volk picture Egor Volk · Aug 29, 2014

Unfortunately it's not possible to do it. 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.

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.