0

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 ?

  • There is no meaning if we add the error to oldMap so just replace the oldMap with newMap and it will work. – itzmukeshy7 Mar 14 '18 at 8:28
  • Did, doesn't work – kabrice Mar 14 '18 at 8:29
  • Are you sure you are getting the same error even after replacing the oldMap with newMap? – itzmukeshy7 Mar 14 '18 at 8:32
  • Sorry, i just edited my post with the real error – kabrice Mar 14 '18 at 8:34
  • With the set of Id's you are not filtering the records in Trigger.new context, then why do you even iterate over records returned by SOQL as they would be same as Trigger.new list? – Raul Mar 14 '18 at 8:35
3

Before insert doesn't have Trigger.newMap as these records not yet inserted into DB, so we don't have Id as key in the Trigger.newMap.

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()){
    // As relatedPrets is not empty it means having some duplicate records so adding error to the list.
    for(Pret__c p: Trigger.new){
      p.addError('Error - dupe item');
    }
  }
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.