0

I am trying to a write what should be a pretty simple trigger to compare an old score with a new score and increment a variable based on the difference. The default field values are set to 0. I thought this would help me get around these sort of null pointer exceptions. The error says it located at line 19. This con.Email_Opens__c = con.Email_Opens +1; Thank you for any help with this.

trigger ClicksAndOpens on Contact (before update) {

for(Contact con  : Trigger.new){
    //Get old Pardot Score
    Contact oldCon = Trigger.oldMap.get(con.Id);
   //set variables to hold old contact and new contact

    Double oldConValue  = oldCon.pi__score__c;
    Double newConValue = con.pi__score__c;


    //add if statement for null pointer value
    if(oldConValue == null){
        oldConValue = 0;
    }
     system.debug('old Pardot score = ' + oldConValue + 'new pardot score = '+ newConValue);
    //determine value of change
    if(newConValue - oldConValue == 1){
        con.Email_Opens__c = con.Email_Opens__c + 1;
        system.debug('Email opens: ' + con.Email_Opens__c);
    }else if(newConValue - oldConValue >= 4){
                con.Email_Opens__c = con.Email_Opens__c +1;
                con.Total_Clicks__c   = con.Total_Clicks__c  + 1;

    }           


}
1
  • Email_Opens__c is null in your case. in the beginning of your code check the value and set the value as 0
    – Himanshu
    Jul 17, 2018 at 18:53

1 Answer 1

3

if you try to add any value in null you will get attempt to reference null object error. you should check value and the make it 0 if it is null. Here is the correct code.

trigger ClicksAndOpens on Contact (before update) {

for(Contact con  : Trigger.new){
    //Get old Pardot Score
    Contact oldCon = Trigger.oldMap.get(con.Id);
   //set variables to hold old contact and new contact

    Double oldConValue  = oldCon.pi__score__c;
    Double newConValue = con.pi__score__c;


    //add if statement for null pointer value
    if(oldConValue == null){
        oldConValue = 0;
    }
     system.debug('old Pardot score = ' + oldConValue + 'new pardot score = '+ newConValue);
    //determine value of change
    if(newConValue - oldConValue == 1){
       //check for null
        con.Email_Opens__c = con.Email_Opens__c!=null ? con.Email_Opens__c + 1 : 0;
        system.debug('Email opens: ' + con.Email_Opens__c);
    }else if(newConValue - oldConValue >= 4){
                con.Email_Opens__c = con.Email_Opens__c +1;
                con.Total_Clicks__c   = con.Total_Clicks__c  + 1;

    }           


}
1
  • Thanks for the quick answer. I thought setting the default field value to 0 would avoid a null pointer exception. Jul 17, 2018 at 19:07

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