You need to sign in to do that
Don't have an account?
Patrick G. Brown
Need a little assistance with Null Pointer Exception
I have a relatively simple trigger that looks through Campaign Members, finds the associated Lead records and checks to see if the Current_Campaign__c field is null on the Lead. If that field is not null, I throw an error. I thought I'd used best practices, however, I'm getting a null pointer exception on this line: if(associatedLead2.Current_Campaign__c!=NULL). The full error reads: checkCurrentCampaign: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object Trigger.checkCurrentCampaign: line 13, column 1
Can anyone see what I may have done? I've tried to edit this a dozen or so different ways to ensure I'm not pulling null records, but I'm still receiving an error. Any assistance would be most appreciated.
My trigger:
Can anyone see what I may have done? I've tried to edit this a dozen or so different ways to ensure I'm not pulling null records, but I'm still receiving an error. Any assistance would be most appreciated.
My trigger:
trigger checkCurrentCampaign on CampaignMember (before insert) { Set<Id> leadIds = new Set<Id>(); for (CampaignMember cml: Trigger.new){ leadIds.add(cml.LeadId); } Map<Id, Lead> LeadMap2 = new Map<Id, Lead>([SELECT Id, Current_Campaign__c, Status FROM Lead WHERE Id IN :leadIds]); //Loop through Campaign Members and get Associated Lead ID for (CampaignMember cml: Trigger.new){ Lead associatedLead2 = LeadMap2.get(cml.LeadId); //Still getting a dereference null error if(associatedLead2.Current_Campaign__c!=NULL) { cml.adderror('Campaign Members can only be in one Campaign at a time. If you are receiving this error, you are attempting to add one or more Leads to multiple active Campaigns'); } } }
For example,
Try this,
trigger checkCurrentCampaign on CampaignMember (before insert) {
Set<Id> leadIds = new Set<Id>();
for (CampaignMember cml: Trigger.new){
leadIds.add(cml.LeadId);
}
if(leadIds.size()>0){
Map<Id, Lead> LeadMap2 = new Map<Id, Lead>([SELECT Id, Current_Campaign__c, Status FROM Lead WHERE Id IN :leadIds]);
//Loop through Campaign Members and get Associated Lead ID
for (CampaignMember cml: Trigger.new){
Lead associatedLead2 = new Lead();
if(LeadMap2.containskey(cml.LeadId)){
associatedLead2 = LeadMap2.get(cml.LeadId);
//Still getting a dereference null error
if(associatedLead2.Current_Campaign__c!=NULL)
{
cml.adderror('Campaign Members can only be in one Campaign at a time. If you are receiving this error, you are attempting to add one or more Leads to multiple active Campaigns');
}
}
}
}
}
If it helps you, please mark is as best answer, so it will be helpful for other developers.
Let us know if this will help you