I have written a trigger handler to prevent more than n incidents for a client(lookup to user) at any point of time. This handler behaves differently if choose (before insert, before update) i.e. the adderror exception occurs only after (n+1) incidents have been created but in case of (after insert,before insert) it works fine.So if the purpose of addError() is to prevent DML operations why does it allows that extra record in case of before events? Also how can I display a dynamic error message in a trigger context.
trigger CountLimit on Incident__c (before insert,before update,after undelete) {
Set<Id> clientids = new Set<Id>();
Map<Id,Integer> clientmap = new Map<Id,Integer>();
for(Incident__c inc:Trigger.new)
{
clientids.add(inc.Client__c);
}
for(AggregateResult result:[select count(id) sum, client__c client from Incident__c where client__C in:clientids group by client__C])
{
clientmap.put((Id)result.get('client'),(Integer)result.get('sum'));
}
for(Incident__c inc:Trigger.new)
{
if(clientmap.get(inc.Client__c)>3)
{
inc.Client__c.addError('You can\'t open more than 3 incidents for '+ inc.Client__r.firstname+' '+inc.Client__r.lastname);
}
}
}