+ Start a Discussion
RaoSRaoS 

Trigger to update custom fields on Lead with values from Custom Object

Hi ,
I am trying to create a trigger to update two custom fields on Lead object with two values from a Custom object. The trigger is getting executed but it is not working as expected i.e. Branch Name and Distance to Branch are not getting populated. 

Here is the Trigger code
trigger UpdateBranchAndDistanceToBranch on Lead (before insert) {
Set<Id> lstLeadsToUpdate = new Set<Id>();    
    for( Lead l : trigger.new )
    {  system.debug('l.PostalCode....' + l.PostalCode);
        //Get the list of all leads that need an update
        If(l.PostalCode != null && l.Branch_Name__C == null )
        {    
            lstLeadsToUpdate.add(l.Id);
        }
    }
    if(lstLeadsToUpdate.isEmpty() == false)
    {
     List<Lead> finallstLeadsToUpdate=new List<Lead>();
     List<Lead> listLeads = [SELECT id,Branch_Name__c,Distance_To_Branch__c, PostalCode  from Lead WHERE Id in :lstLeadsToUpdate];
       system.debug('listLeads ...' + listLeads);
     For (Lead oLead : listLeads) 
        {   
         Serviced_Postal_Code__c sp=[select Sub_Branch__c,Distance_From_Branch_mi__c from Serviced_Postal_Code__c where Postal_Code__c= : oLead.PostalCode];
         Lead c=new Lead(Id=oLead.Id);
       
         system.debug('sp.Sub_Branch__c..' + sp.Sub_Branch__c);
         system.debug('sp.Distance_From_Branch_mi__c..' + sp.Distance_From_Branch_mi__c);
       
         c.Branch_Name__c =  sp.Sub_Branch__c;
         c.Distance_To_Branch__c  =  sp.Distance_From_Branch_mi__c; 
         finallstLeadsToUpdate.add(c);   
         }  
      
        if (finallstLeadsToUpdate.size()>0)
           {
                update finallstLeadsToUpdate;
            }  
    }               

}
First debug statement(system.debug('l.PostalCode....' + l.PostalCode);) is displaying the postal code that i am keying in for the lead.
The debug log is showing zero rows for "SELECT id,Branch_Name__c,Distance_To_Branch__c, PostalCode  from Lead WHERE Id in :lstLeadsToUpdate"

I am unable to figure out what am I missing in the code that is causing the issue.

Kindly let me know where am I going wrong.

Thanks
Rao

 
Best Answer chosen by RaoS
Banwari KevatBanwari Kevat
Hi,
  Please run this code. You don't need to take care of update statement. Recordds automatically committed into database.
trigger UpdateBranchAndDistanceToBranch on Lead (before insert) {
Set<String> postalCodeList = new Set<String>();
List<Lead> leadList = new List<Lead>();    
    for( Lead l : trigger.new )
    {  
        If(l.PostalCode != null && l.Branch_Name__C == null )
        {    
            postalCodeList.add(l.PostalCode);
			leadList.add(l);
        }
    }
	
    Map<String, Serviced_Postal_Code__c> codeBrachMap = new Map<String, Serviced_Postal_Code__c>();
	for(Serviced_Postal_Code__c spc : [SELECT Sub_Branch__c,Postal_Code__c,Distance_From_Branch_mi__c FROM Serviced_Postal_Code__c 
        WHERE Postal_Code__c IN :postalCodeList]){
		codeBrachMap.put(spc.Postal_Code__c, spc);
	}
	for(Lead ld : leadList){
	     Serviced_Postal_Code__c tempSPC = codeBrachMap.get(ld.PostalCode);
		 ld.Branch_Name__c = tempSPC.Sub_Branch__c;
		 ld.Distance_To_Branch__c = tempSPC.Distance_From_Branch_mi__c;
	}
	      

}

If you have any query you can ping me directly. If you got ypur answer please mark it as best answer so that othes can get help.

Thanks,
Banwari
skype: bkevat92
 

All Answers

Banwari KevatBanwari Kevat
Hi,
   You are trying to qurey on Lead records which are not yested yet. Because in before insert context Id of the record is not assigned.
That is why there is zero row.

Thanks,
Banwari
Banwari KevatBanwari Kevat
Hi,
  Please run this code. You don't need to take care of update statement. Recordds automatically committed into database.
trigger UpdateBranchAndDistanceToBranch on Lead (before insert) {
Set<String> postalCodeList = new Set<String>();
List<Lead> leadList = new List<Lead>();    
    for( Lead l : trigger.new )
    {  
        If(l.PostalCode != null && l.Branch_Name__C == null )
        {    
            postalCodeList.add(l.PostalCode);
			leadList.add(l);
        }
    }
	
    Map<String, Serviced_Postal_Code__c> codeBrachMap = new Map<String, Serviced_Postal_Code__c>();
	for(Serviced_Postal_Code__c spc : [SELECT Sub_Branch__c,Postal_Code__c,Distance_From_Branch_mi__c FROM Serviced_Postal_Code__c 
        WHERE Postal_Code__c IN :postalCodeList]){
		codeBrachMap.put(spc.Postal_Code__c, spc);
	}
	for(Lead ld : leadList){
	     Serviced_Postal_Code__c tempSPC = codeBrachMap.get(ld.PostalCode);
		 ld.Branch_Name__c = tempSPC.Sub_Branch__c;
		 ld.Distance_To_Branch__c = tempSPC.Distance_From_Branch_mi__c;
	}
	      

}

If you have any query you can ping me directly. If you got ypur answer please mark it as best answer so that othes can get help.

Thanks,
Banwari
skype: bkevat92
 
This was selected as the best answer
RaoSRaoS
HI Banwari,
Thank you for the help.  I have modified my code to what you gave.  I am getting the following error.

Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger UpdateBranchAndDistanceToBranch caused an unexpected exception, contact your administrator: UpdateBranchAndDistanceToBranch: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.UpdateBranchAndDistanceToBranch: line 72, column 1

Line 72 is: ld.Branch_Name__c = tempSPC.Sub_Branch__c;

Thanks
Rao
Banwari KevatBanwari Kevat
Hi Raos,
   Please change the code from li 18 to 22 as below
for(Lead ld : leadList){
	     Serviced_Postal_Code__c tempSPC = codeBrachMap.get(ld.PostalCode);
            if(tempSPC  != null)		
                 ld.Branch_Name__c = tempSPC.Sub_Branch__c;
		         ld.Distance_To_Branch__c = tempSPC.Distance_From_Branch_mi__c;
              }
	}

This error is occuring becuase your org data don't get setup properly. In other words for every postalcode there should be exist a Serviced_Postal_Code__c record in your org.
Lets say your postalCode on Lead is YU890K and there is no exists a record for Serviced_Postal_Code__c  object. Then whenever you try to get barnch name for this postal code, definity you get an error reagarding null pointer.

Thanks,
Banwari
RaoSRaoS
Thank you Banwari.

I have modified the code according to your new code.  I am not getting any error now.  LEad is getting created.  But the Branch Name and Distance fields are not getting populated.  When I debugged the code the following sql (in bold) is not returning any rows.
for(Serviced_Postal_Code__c spc : [SELECT Sub_Branch__c,Postal_Code__c,Distance_From_Branch_mi__c FROM Serviced_Postal_Code__c WHERE Postal_Code__c IN :postalCodeList]){
    system.debug('spc.Postal_Code__c..' + spc.Postal_Code__c);
        codeBrachMap.put(spc.Postal_Code__c, spc);

    }

Here is the log message
09:24:11.0 (28017059)|SOQL_EXECUTE_BEGIN|[60]|Aggregations:0|SELECT Sub_Branch__c, Postal_Code__c, Distance_From_Branch_mi__c FROM Serviced_Postal_Code__c 09:24:11.0 (32921086)|SOQL_EXECUTE_END|[60]|Rows:0

Let me know if i am missing anything here.

Thanks
Rao
RaoSRaoS
Hi Banwari,
I have modified my code and now the query is returning a row.  But the lines that i have marked in Bold is where it is failing as my debug statement 'tempSPC..' is coming as null.

Set<String> postalCodeList = new Set<String>();

List<Lead> leadList = new List<Lead>();   

    for( Lead l : trigger.new )

    { 
system.debug('1 l.PostalCode..' + l.PostalCode);
        If(l.PostalCode != null && l.Branch_Name__C == null )

        {   
system.debug('2 l.PostalCode..' + l.PostalCode);
            postalCodeList.add(l.PostalCode);

            leadList.add(l);

        }

    }
system.debug('postalCodeList..' +postalCodeList);
     

    Map<String, Serviced_Postal_Code__c> codeBrachMap = new Map<String, Serviced_Postal_Code__c>();

//    for(Serviced_Postal_Code__c spc : [SELECT Sub_Branch__c,Postal_Code__c,Distance_From_Branch_mi__c FROM Serviced_Postal_Code__c WHERE Postal_Code__c IN :postalCodeList]){
    for(Serviced_Postal_Code__c spc : [SELECT Sub_Branch__c,Postal_Code__c,Distance_From_Branch_mi__c FROM Serviced_Postal_Code__c WHERE Postal_Code__c IN 
                                       (select Id from Postal_Code__c where Name IN :postalCodeList)]){

    system.debug('spc.Postal_Code__c..' + spc.Postal_Code__c);
        codeBrachMap.put(spc.Postal_Code__c, spc);

    }

for(Lead ld : leadList){
    Serviced_Postal_Code__c tempSPC = codeBrachMap.get(ld.PostalCode);
    system.debug('tempSPC..' +tempSPC);
    if(tempSPC  != null)  
    {system.debug('2 tempSPC.Sub_Branch__c..' + tempSPC.Sub_Branch__c);
    system.debug('2 tempSPC.Distance_From_Branch_mi__c..' + tempSPC.Distance_From_Branch_mi__c); 
        ld.Branch_Name__c = tempSPC.Sub_Branch__c;
        ld.Distance_To_Branch__c = tempSPC.Distance_From_Branch_mi__c;
              }
    }

I am not sure what I am missing here.

Let me know.

Thanks
Rao
Banwari KevatBanwari Kevat
Hi Rao,
  This the issue of your org data. And also I'm not clear of you data model.
Can you please DM on skype: bkevat92
Thanks
Banwari
RaoSRaoS
Thanks Banwari.  I made changes according to your suggestions.
Here is the final code.
trigger UpdateBranchAndDistanceToBranch on Lead (before insert) {
Set<String> postalCodeList = new Set<String>();

List<Lead> leadList = new List<Lead>();   
    for( Lead l : trigger.new )
    { 
        If(l.PostalCode != null && l.Branch_Name__C == null )
        {   
            postalCodeList.add(l.PostalCode);
            leadList.add(l);
        }
    }   

    Map<String, Serviced_Postal_Code__c> codeBrachMap = new Map<String, Serviced_Postal_Code__c>();

Serviced_Postal_Code__c WHERE Postal_Code__c IN :postalCodeList]){
    for(Serviced_Postal_Code__c spc : [SELECT Sub_Branch__c,Sub_Branch__r.Name,Postal_Code__r.Name,Distance_From_Branch_mi__c FROM Serviced_Postal_Code__c WHERE Postal_Code__r.Name IN :postalCodeList])
{
        codeBrachMap.put(spc.Postal_Code__r.Name, spc);

    }

for(Lead ld : leadList){
    Serviced_Postal_Code__c tempSPC = codeBrachMap.get(ld.PostalCode);
    if(tempSPC  != null)  
    {
        ld.Branch_Name__c = tempSPC.Sub_Branch__r.Name;
        ld.Distance_To_Branch__c = tempSPC.Distance_From_Branch_mi__c;
              }
    }

}