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 ?

7
  • There is no meaning if we add the error to oldMap so just replace the oldMap with newMap and it will work. Commented Mar 14, 2018 at 8:28
  • Did, doesn't work
    – kabrice
    Commented Mar 14, 2018 at 8:29
  • Are you sure you are getting the same error even after replacing the oldMap with newMap? Commented Mar 14, 2018 at 8:32
  • Sorry, i just edited my post with the real error
    – kabrice
    Commented Mar 14, 2018 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
    Commented Mar 14, 2018 at 8:35

1 Answer 1

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');
    }
  }
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .