function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Caleb_SidelCaleb_Sidel 

addError to a field on an SObject?

Has anyone successfully used addError on a field dynamically on an SObject?

 

Something like the below in concept (note the below doesn't work because get(FieldName) returns the value in that field, not the field itself...

 

Account a = [Select fields FROM Account WHERE stuff];

SObject obj = (SObject)a;

obj.get('FieldName__c').addError('Something or other');

 

Thank you,

Caleb

 

salesforce expertsalesforce expert

this would solve your issue.

 

obj.<field name>.addError('<error text>');

 

 

let me know if this helps you!

 

Baskaran

Caleb_SidelCaleb_Sidel

True, that works if I know the field name... but what if I wanted to something like

 

Map<String,String> fieldNameToError;

 

for(String fieldName : fieldNameToError.keySet)

 

obj.get(fieldName).addError(fieldNameToError.get(fieldName));

 

In the above case fieldName isn't known. It's a contrived example, in my actual use case I have two objects a parent and a child and they share some field names. I want if the child record errors on a field name that they share to have an error on the parent on the same field. Currently I'm doing something similar to

 

Map<String,String> fieldNameToError;

 

for(String fieldName : fieldNameToError.keySet)

 

if(fieldName.equalsIgnoreCase('Field1__c')) obj.Field1__c.addError(fieldNameToError.get(fieldName));

else if(fieldName.equalsIgnoreCase('Field2__c')) obj.Field2__c.addError(fieldNameToError.get(fieldName));

else if...

else obj.addError(fieldNameToError.get(fieldName));

 

But if someone adds a new field...code change :(

 

Thanks for any help :)

 

 

 

Meer ZamanMeer Zaman
Hi @Caleb_Sidel,

This is now available in Salesforce Winter ’21 Release, check the link (https://releasenotes.docs.salesforce.com/en-us/winter21/release-notes/rn_apex_trackErrors.htm) for detail
//Baseline code sample for using addError, getErrors, together
Account a = new Account();
String msg = 'New error method in SObject';
//The new overload that accepts the field dynamically at runtime
a.addError('Name', msg); 
List<Database.Error> errors = a.getErrors();
System.assertEquals(1, errors.size());
Database.Error error = errors.get(0);
System.assertEquals(msg, error.getMessage());
System.assertEquals(StatusCode.FIELD_CUSTOM_VALIDATION_EXCEPTION, error.getStatusCode());
String[] fields = error.getFields();
System.assertNotEquals(null, fields);
System.assertEquals(1, fields.size());

Thanks,
Meer Zaman