I am trying to display an error message if a field on Quote is updated to a certain value. I am doing it on before update but I am encountering an error
Here is a sample code block I am trying on my org
Best Answer
Been a while since I used it but the docs state Trigger.New...
Triggers can be used to prevent DML operations from occurring by
calling the addError() method on a record or field. When used on
Trigger.new records in insert and update triggers, and on Trigger.old
records in delete triggers, the custom error message is displayed in
the application interface and logged.
Now I've just tested for myself, the following works:
trigger ContactTrigger on Contact (before insert, before update) {
contactUtils.testAddError(trigger.new);
}
public class contactUtils {
public static void testAddError(List<Contact> conList){
for(Contact con : conList){
con.addError('nope.');
}
}
}
In the case of a before-trigger the query in the for-loop only returns three records in the AggregateResult, because the fourth record has not been inserted yet. In the case of an after-trigger, however, the record has already been inserted, so the query returns four records and the error shows.
I suggest that you change your code inside the last for-loop to:
if((Trigger.isUpdate && clientmap.get(inc.Client__c) > 3) ||
(Trigger.isBefore && clientmap.get(inc.Client__c) > 2)) {
inc.Client__c.addError('You can\'t open more than 3 incidents for '+ inc.Client__r.firstname+' '+inc.Client__r.lastname);
}
With regards to your dynamic message, you can't use object-relations this way in triggers. You will have to retrieve all clients first, add them to a map and then you can use them.
Actually addError() do support HTML markups to beautify your error message.
addError(exceptionError, escape)
So i give this method a try, here is my result:
Without HTML markup:
a.addError('account can not be deleted');
With HTML Markup:
a.addError('<h1><i>account can not be deleted</i></h1>', false);
There are some Con's of using this method as default addError method escapes any HTML string and here you are stopping it from doing so. So be aware of it before using it.
Be cautious if you specify false for the escape argument. Unescaped
strings displayed in the Salesforce user interface can represent a
vulnerability in the system because these strings might contain
harmful code. If you want to include HTML markup in the error message,
call this method with a false escape argument and make sure you escape
any dynamic content, such as input field values. Otherwise, specify
true for the escape argument or call addError(String errorMsg)
instead.
Best Answer
Been a while since I used it but the docs state
Trigger.New
...https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_triggers_exceptions.htm
Now I've just tested for myself, the following works: