Search code examples
triggerssalesforceapex-code

Apex Salesforce Updating Field from Other Entity only getting 1 value on Bulk insert


Tried to make that title as specific as possible. Sorry if it is long. Basically, what is happening is that I have a trigger that looks up a match (on email) to a custom object. If the email matches. I need to pull information from the custom object (Member Verification) and put that in a field (custom field) on the Lead object.

This is working fine for individuals. But when I do a bulk import, every Lead ends up with the same value, instead of the unique value that it should be matching by email address. I have tried about 6 different methods, and all of them look like they should work. But I have no idea what I am missing. Any help would be greatly appreciated.

The code is below:

trigger UpdateVerifyLead on Lead (before insert, before update) {
List<String> leadEmails = new List<String>();

Map<String, Member_Verification__c > MVEmailMap = new  Map<String, Member_Verification__c >(
    [SELECT Id, Primary_Email__c,TFA_Salesforce_ID__C FROM Member_Verification__c WHERE Primary_Email__c != null and Primary_Email__c IN :leadEmails]);

for(Lead lead:Trigger.new){
    leadEmails.add(lead.Email);

for(Lead leadObj:Trigger.new){
    if(MVEmailmap.containsKey(leadObj.Email)){
        lead.TFA_Salesforce_ID__c = MVEmailmap.get(leadObj.Email).TFA_Salesforce_ID__C ;
        lead.Verified__c = True;
        MVEmailmap.clear();
    }
    }

}


Solution

  • You're instantiating the map using a query, which is fine if you need to have Ids as keys, but I'm not sure it works with your email field as a key.

    You'll need an extra iteration to populate the map.

    Something like this should work:

       trigger UpdateVerifyLead on Lead (before insert, before update) {
    
         List<String> leadEmails = new List<String>();
         Map<String, Member_Verification__c> MVEmailMap = new  Map<String, Member_Verification__c>();
    
         // first iteration to get the emails
         for(Lead lead:Trigger.new){
           leadEmails.add(lead.Email);
         }
    
         // populate the map, dropping the != null, shouldn't be necessary
         for(Member_Verification__c memberVerification:[SELECT Id, Primary_Email__c,TFA_Salesforce_ID__C FROM Member_Verification__c WHERE Primary_Email__c IN :leadEmails]){
             MVEmailMap.put(memberVerification.Primary_Email__c,memberVerification);
         }
    
         // final iteration to set the member verification
         for(Lead leadObj:Trigger.new){
             if(MVEmailmap.containsKey(leadObj.Email)){
                 lead.TFA_Salesforce_ID__c = MVEmailmap.get(leadObj.Email).TFA_Salesforce_ID__C;
                 lead.Verified__c = True;
              }
         }
      }