Apex Salesforce从其他实体更新字段仅在批量插入时获得1个值

时间:2014-11-01 04:26:13

标签: triggers salesforce apex-code

试图让这个标题尽可能具体。对不起,如果它很长。 基本上,发生的事情是我有一个触发器,用于查找匹配(在电子邮件中)到自定义对象。如果电子邮件匹配。我需要从自定义对象(成员验证)中提取信息,并将其放在Lead对象的字段(自定义字段)中。

这对个人来说很好。但是当我进行批量导入时,每个Lead都会以相同的值结束,而不是通过电子邮件地址匹配的唯一值。我尝试了大约6种不同的方法,所有这些方法看起来都应该有效。但我不知道我错过了什么。任何帮助将不胜感激。

代码如下:

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();
    }
    }

}

1 个答案:

答案 0 :(得分:0)

您使用查询来实例化地图,如果您需要have Ids as keys,这很好,但我不确定它是否适用于您的电子邮件字段作为密钥。

您需要额外的迭代才能填充地图。

这样的事情应该有效:

   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;
          }
     }
  }