2017-04-12 232 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; 
}