Update Contacts’ Mailing Address via SOQL

Using Parent-Child SOQL, this trigger copies changes in an Account’s Billing Address to the Mailing Address of all related Contacts.

Practice similar triggers here: YouTube playlist.

Solution:

trigger AccountTrigger on Account (after update) {
         if(Trigger.isUpdate){ if(Trigger.isAfter){
                                   AccountTriggerHandler.updateRelatedConts(Trigger.New, Trigger.oldMap);
                         }
          }
}
public class AccountTriggerHandler {

          public static void updateRelatedContactMailWithoutMap(List<Account> accList,Map<Id,Account>
oldMap){
                List conList=new List(); Set idSet= new Set(); for(Account
                 acc:accList){ if((!acc.BillingCity.equals(oldMap.get(acc.Id).BillingCity) ||
                 !acc.BillingCountry.equals(oldMap.get(acc.Id).BillingCountry) ||
                 !acc.BillingPostalCode.equals(oldMap.get(acc.Id).BillingPostalCode)
|| !acc.BillingState.equals(oldMap.get(acc.Id).BillingState) ||
!acc.BillingStreet.equals(oldMap.get(acc.Id).BillingStreet) ) && oldMap!=null){ idSet.add(acc.Id);
                             }
                    }
                     for(Account acc:[SELECT Id, BillingCountry, BillingCity, BillingState,
        BillingPostalCode, BillingStreet, (SELECT Id FROM Contacts) FROM
         Account WHERE Id IN:idSet]) {
                                        if(acc.Contacts!=null){ for(Contact cont:acc.Contacts){
                                        cont.MailingCountry=acc.BillingCountry; cont.MailingCity= acc.BillingCity;
                                        cont.MailingState=acc.BillingState;
                                        cont.MailingPostalCode=acc.BillingPostalCode;
                                        cont.MailingStreet=acc.BillingStreet;
                                        conList.add(cont);
                                        }
                              }
                    }
                     if(!conList.isEmpty()){ update conList;
                    }
         }
}

Want to Apply As Content Writer?

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Cart

Let's get you started!

Interested in writing Salesforce Content?

Fill in this form and we will get in touch with you :)