+ Start a Discussion
NecroGigglesNecroGiggles 

System.NullPointerException with date field

My problem is that whenever we delete the date info from Response_Tracking_Date__c  on a Campaign Member object I get an error.
"System.NullPointerException: Attempt to de-reference a null object: Trigger.CampaignMemberTrigger: line 10, column 1"

I am not sure what I need to do to the code to get around this problem. I was thinking an if statement between the 2 for loops on line 5 and 6. 

 
trigger CampaignMemberTrigger on CampaignMember (before insert, before update) {
    // Get a list of fields from the sObject Marketing_KPI_Target__c and name the list kpiTargetList
    List<Marketing_KPI_Target__c> kpiTargetList = [SELECT Type_of_Sale__c, ECI_Product__c, CurrencyIsoCode,KPI_Target_Date__c FROM Marketing_KPI_Target__c];
    
    for (CampaignMember member : Trigger.New) {
        for (Marketing_KPI_Target__c kpiTarget : kpiTargetList) {
            if (kpiTarget.Type_of_Sale__c == member.Type_of_Sale__c &&
                kpiTarget.ECI_Product__c == member.ECI_Product__c &&
                kpiTarget.CurrencyIsoCode == member.CurrencyIsoCode &&
               	kpiTarget.KPI_Target_Date__c.month() == member.Response_Tracking_Date__c.month() &&
				kpiTarget.KPI_Target_Date__c.year() == member.Response_Tracking_Date__c.year() &&
                member.HasResponded == True)
            {
                member.Marketing_KPI_Target__c = kpiTarget.Id;
                continue;
            }
        }
    }
}


 
Best Answer chosen by NecroGiggles
Amit Chaudhary 8Amit Chaudhary 8
Add null check for date field like below
trigger CampaignMemberTrigger on CampaignMember (before insert, before update) {
    // Get a list of fields from the sObject Marketing_KPI_Target__c and name the list kpiTargetList
    List<Marketing_KPI_Target__c> kpiTargetList = [SELECT Type_of_Sale__c, ECI_Product__c, CurrencyIsoCode,KPI_Target_Date__c FROM Marketing_KPI_Target__c];
    
    for (CampaignMember member : Trigger.New) {
        for (Marketing_KPI_Target__c kpiTarget : kpiTargetList) {
            if (kpiTarget.Type_of_Sale__c == member.Type_of_Sale__c &&
                kpiTarget.ECI_Product__c == member.ECI_Product__c &&
                kpiTarget.CurrencyIsoCode == member.CurrencyIsoCode &&
               	kpiTarget.KPI_Target_Date__c != null && member.Response_Tracking_Date__c != null && 
				kpiTarget.KPI_Target_Date__c.month() == member.Response_Tracking_Date__c.month() )&&
				kpiTarget.KPI_Target_Date__c.year() == member.Response_Tracking_Date__c.year() &&
                member.HasResponded == True)
            {
                member.Marketing_KPI_Target__c = kpiTarget.Id;
                continue;
            }
        }
    }
}
Let us know if this will help you

Thanks