Error: There was an error creating Lead 1. Salesforce error:
dlrs_LeadTrigger: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object Class.Helper.populateparnerId: line 23, column 1 Trigger.dlrs_LeadTrigger: line 9, column 1
So I am working on two object:
-Leads
-Partner object(Custom)
So I have a before insert Trigger on Leads, so when a new Lead is created and Partner Number Field is not blank it has to lookup for Partner_Number_Copy__c field on the Partner Object and return its Partner ID
Following Code works fine if I manually create a lead and provide a Partner Number it is populating a Partner__c field which is a lookup field to Partner object.
But when Leads are created through a Web Form I am receiving the above error.
FYI: Line 26 in the code is l.Partner__c=mapIdByPartner.get(l.Partner_Number__c).id;
`
public class Helper{
public static void populateparnerId(list<Lead> lstlead){
set<decimal> setpartnerIds=new set<decimal>();
for(Lead l:lstlead){
if(l.Partner_Number__c!=null){
setpartnerIds.add(l.Partner_Number__c);
}
}
//Query partner records
map<decimal,Partner__c> mapIdByPartner=new map<decimal,Partner__c>();
for(Partner__c p:[Select Id,Partner_Number_Copy__c from Partner__c where Partner_Number_Copy__c in:setpartnerIds]){
mapIdByPartner.put(p.Partner_Number_Copy__c,p);
}
for(lead l:lstlead){
if(l.Partner_Number__c!=null){
l.Partner__c=mapIdByPartner.get(l.Partner_Number__c).id;
}
}
}
}
`
Trigger used (also Line 9 from the error message),
if(trigger.isInsert && trigger.isBefore){
Helper.populateparnerId(trigger.new);
}
Best Answer
Consider the following situation:
A Lead is coming with
Partner_Number__c = '123'
('123' != null). If you do not have Partner__c record with such Partner_Number_Copy__c thenmapIdByPartner.get(l.Partner_Number__c)
will returnnull
and it obviously has no Id. So you might want to modify your code as follows :if(l.Partner_Number__c != null && mapIdByPartner.get(l.Partner_Number__c) != null){ l.Partner__c = mapIdByPartner.get(l.Partner_Number__c).id; }
This way you`ll be ready for situations when there will be no records with incoming Partner_Number__c in your system.