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
GoForceGoGoForceGo 

Using addError to add multiple Errors.

The following code only shows Error 2. How can one modify it to show both errors (short of accumulating all errors and showing as one large string).

trigger testAccountError on Account (after insert) {


        for (Accout a: Trigger.New) {
            a.addError('Error 1');
            a.addError('Error 2');
        }

}
PrabhaPrabha
It does that because it is addError, not addErrors. ;)

If you want to show new line in the message, u might try '</br>' or  '\n' in the addError(), something like this:
string br = '</br>';
a.addError('Error 1'+br+'Error 2 ');

hth
Prabhan
Rohith Kumar 98Rohith Kumar 98
Something like this should work for adding collective errors.
 
trigger testAccountError on Account(after insert){
	Map<Account, String> mapOfAccountWithErrorMessages = new Map<Account, String>();
	for(Accout eachAccount: Trigger.New){
		if(mapOfAccountWithErrorMessages.containsKey(eachAccount){
			String existingError = mapOfAccountWithErrorMessages.get(eachAccount);
			String newError = existingError + ', ' + 'Error 2';
			mapOfAccountWithErrorMessages.put(eachAccount, newError);
		}
		else{
			mapOfAccountWithErrorMessages.put(eachAccount, 'Error 1');
		}
	}
	for(Accout eachErroredAccount: mapOfAccountWithErrorMessages.keySet(){
		eachErroredAccount.addError(mapOfAccountWithErrorMessages.get(eachErroredAccount));
	}
}

 
Arun Kumar 1141Arun Kumar 1141

Hi,

 

In Salesforce triggers, you can't directly display multiple error messages for a single record using addError. It's designed to add a single error message for a record. If you add multiple addError statements, only the last error message will be displayed.
To work around this limitation and display multiple error messages, you can accumulate the errors into a collection (e.g., a List) and then display them as a single error message. Here's how you can modify your trigger to display both errors:

trigger testAccountError on Account (before insert) {
    List<String> errorMessages = new List<String>();

    for (Account a : Trigger.New) {
        errorMessages.add('Error 1');
        errorMessages.add('Error 2');
    }

    if (!errorMessages.isEmpty()) {
        String errorMessage = String.join(errorMessages, ', ');
        Trigger.New[0].addError(errorMessage);
    }
}


I hope this will help you.

Thanks!