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
VijayNiVijayNi 

trigger to update contact name whenever account name is updated

Hi ALL,

can someoene help me in updating the trigger whenever name is updated in account contact should be also updatedwith same name


write a trigger whenever name is updated on account the same value should be populated on contact 

trigger name on account (before update)
{
set <id> List = new  set<id> [select ID,city,name from account where id in:trigger.new]

for (account a : trigger.new)
if(a.id=list.id)
{
a.name=list.name;

}

}
Best Answer chosen by VijayNi
SwethaSwetha (Salesforce Developers) 
HI Vijay,

It is a best practice to use helper class when writing triggers. Try this
ContactNameUpdate.apxt
trigger ContactNameUpdate on Account (after Update) {
if(trigger.isUpdate && trigger.isAfter){
 accountNameUpdate.accountMethod(trigger.new,trigger.oldmap); }}
accountNameUpdate.apxc
public class accountNameUpdate {
public static void accountMethod(List<Account>aclist,map<id,account> oldmap){
    set<id> accountId=new set<id>();
    for(Account ac:aclist){
        account accountOld=oldmap.get(ac.id);
        if(ac.Name!=accountOld.Name){
            accountId.add(ac.Id);
        }
    }

    if(accountId.size()>0){
        map<id,account> accountmap=new map<id,account>([select id,Name,(select id,LastName from contacts) from account where id in:accountId]);
        List<contact> clist=new List<contact>();
        for(account ac:aclist){
            account accountOld=oldmap.get(ac.id);
            if(ac.Name!=accountOld.Name){
                if(accountmap.containskey(ac.id)){
                    account ac1=accountmap.get(ac.id);
                    List<contact>lstCont = ac1.contacts;
                    for(contact c:lstCont){
                        c.LastName=ac.Name;
                        clist.add(c);
                    }

                }
            }
        }
        if(!clist.isEmpty()){
            update clist;
        }

    }
}}
Based on https://salesforce.stackexchange.com/questions/200019/update-contacts-phones-with-account-phone-using-trigger

Hope this helps you. Please mark this answer as best so that others facing the same issue will find this information useful. Thank you