2017-04-12 4 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; 
} 
関連する問題