2017-04-12 243 views
1

帐户和联系人都有Billing_Address__c字段。联系人也有复选框称为active__c。如果active__c为true并且Account Billing_Address__c更新,则更新Contact的Billing_Address__c。这是触发器。它工作正常。但是我想知道是否有任何问题,或者如何根据内存条件对此进行优化?触发帐户更新联系人

public static void updateContactBillingAddress(List<Account> lstNew, Map<Id,Account> mapOld){ 
    Set<Id> accIds = new Set<Id>(); 
    for(Account acc : lstNew){ 
     if(acc.Billing_Address__c != mapOld.get(acc.Id).Billing_Address__c && acc.Billing_Address__c !=null){ 
      accIds.add(acc.Id); 
     } 
    } 
    if(!accIds.isEmpty()){ 
     List<Contact> lstContact = new List<Contact>([Select ID,active__c, Account.Billing_Address__c,Billing_Address__c FROM Contact where AccountID IN :accIds]); 
     List<Contact> lstUpdateCon = new List<Contact>(); 
     for(Contact con : lstContact){ 
      if(con.active__c == true){ 
       if(con.Billing_Address__c != con.Account.Billing_Address__c){ 
        con.Billing_Address__c = con.Account.Billing_Address__c; 
        lstUpdateCon.add(con); 
        } 
      } 
      else{ 
       con.Billing_Address__c =null; 
       lstUpdateCon.add(con); 
      } 
     } 
     if(!lstUpdateCon.isEmpty()){ 
      update lstUpdateCon; 
     } 
    } 
} 
+0

的可能的复制[触发帐户更新联系人字段(http://stackoverflow.com/questions/43397554/trigger-on-account-to-update-contact-field) – Jaiman

回答

1

不是,它的语义,但我会返回一个联系人,1方法,1件事情。您正在处理帐户并更新它们,我会返回联系人的List,而不是使用相同的方法更新它们。如果您需要沿着道路行驶update contacts,您最终会做出不必要的DML语句,您也不需要为该循环创建List

public static List<Contact> updateContactBillingAddress(List<Account> lstNew, Map<ID,Account> mapOld) 
{ 
    List<Contact> result = new List<Contact>(); 

    Set<Id> accIds = new Set<Id>(); 

    for(Account acc : lstNew) 
    { 
     if(acc.Billing_Address__c != null && acc.Billing_Address__c != mapOld.get(acc.Id).Billing_Address__c) 
     { 
      accIds.add(acc.Id); 
     } 
    } 

    if(!accIds.isEmpty()) 
    {   
     for(Contact con : [Select ID,Active__c, Account.Billing_Address__c,Billing_Address__c FROM Contact where AccountID IN :accIds]) 
     { 
      if(con.Active__c == true){ 
       if(con.Billing_Address__c != con.Account.Billing_Address__c) 
       { 
        con.Billing_Address__c = con.Account.Billing_Address__c; 
        result.add(con); 
       } 
      } 
      else 
      { 
       con.Billing_Address__c = null; 
       result.add(con); 
      } 
     } 
    } 

    return result; 
}