I created a trigger that work very except that I got this error when I try to use addError :
MyTestTrigger: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.MyTestTrigger: line 19, column 1
Here is my trigger:
trigger CheckDupesTrigger on Pret__c (before insert) {
Set<Id> livreNew = new Set<Id>{};
Set<Id> contactNew = new Set<Id>{};
for(Pret__c p: Trigger.new){
livreNew.add(p.Livre__c);
contactNew.add(p.Contact__c);
}
List<Pret__c> relatedPrets = [SELECT Id, Contact__c, Livre__c FROM Pret__c
WHERE Livre__c IN :livreNew AND Contact__c IN :contactNew];
system.debug('relatedPrets '+relatedPrets);
if(!relatedPrets.isEmpty()){
for(Pret__c p: relatedPrets){
system.debug('Trigger p.Id '+p.Id);
Trigger.newMap.get(p.Id).addError('Error - dupe item'); //I've tried with oldMap, still failed
}
}
}
Pret__c
is a junction object between Livre__c
and Contact__c
Edit:
I saw that p.Id has a value in the debug console.
Where I'm wrong ?
oldMap
so just replace theoldMap
withnewMap
and it will work.oldMap
withnewMap
?Trigger.new
context, then why do you even iterate over records returned by SOQL as they would be same asTrigger.new
list?