function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Olivera MilevskaOlivera Milevska 

Hello, I would like to write a trigger code to update the contacts address automatically when it is updated for the account ? Can you please assist with the code?

Amit Chaudhary 8Amit Chaudhary 8
Please try below code :-
trigger changeAddress on Account ( after update ) 
{
	List<contact> listCont=new List<contact>();
	Map<string,List<Contact>> cMap = new Map<string,List<Contact>>();

	List<Account> lstAcc = new List<Account>();

	for(Account A : Trigger.New)
	{
		if(A.BillingCity != Trigger.OldMap.get(A.id).BillingCity )
		{
			lstAcc.add(A);
		}
	}
  
	listCont = [select id,accountid,MailingCity from contact where accountid in :lstAcc];

	for(Contact c : listCont)
	{
		if(cMap.containsKey(c.Accountid) == false)
		{
			List<Contact> lstC = new List<Contact>();
			lstC.add(c);
			cMap.put(c.Accountid, lstC);
		}
		else
		{
			List<Contact> lstC = cMap.get(c.Accountid);
			lstC.add(c);
		}
	}

	for(Account A : lstAcc)
	{
		if(cMap.containsKey(A.id))
		{
			List<Contact> lstC = cMap.get(A.id);
			for(Contact C : lstC)
			{
				C.MailingCity = A.BillingCity;
			}
		}
	}
	
	if(listCont.size() > 0)
	{
		update listCont;
    }
}

NOTE :- I have added only BillingCity please add all other field according to your requirement.

Please mark this as solution if this will help you.

Thanks
Amit Chaudhary