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 Lastname on contact object whenever Lastname is updated on account object

Hi  All,

can you help me on writting the trigger whenever name is updated on account contact name also should be updated.
1. I am updating  using the related filed id condition 
trigger accountname on Account (before insert) {
    list<contact> contacts = new list<contact>();
    set<id> accountd = new set<id>
accountid =  [select idrom contact where id in :trigger.new]
    lis<contacts> con = new list[slect id,name from contacts where id in :accountd]
    for(account acc : trigger.new){
      if(acc.id ==accountd.id)
         {
            con.LastName = acc.Lastname;
            contacts.add(con);
        }
    }update contacts;
}
SwethaSwetha (Salesforce Developers) 
HI Vijay,
I was wondering if you were able to take a look at the solution I posted on 
https://developer.salesforce.com/forums/ForumsMain?id=9062I000000IVTDQA4 which seems to be the same as this question.

If you are looking for something else, can you elaborate so I can suggest better? If this information helps, please mark the answer as best.Thank you
ravi soniravi soni
Hi ummeda vijay,
 try this following trigger. 
trigger updateContactNameWithAccount on Account (after update) {
    
    if(trigger.isAfter){
        if(trigger.isUpdate){
            set<Id> accSetId = new set<Id>();
            map<Id,string> AccountRecMap = new map<Id,string>();
            
            list<contact> lstContact = new list<contact>(); 
            for(Account acc : trigger.new){
                AccountRecMap.put(acc.Id,acc.Name);
            accSetId.add(acc.Id);    
            }
            system.debug('AccountRecMap===> ' + AccountRecMap);
            
            for(contact con : [SELECT Id,LastName,AccountId From Contact Where AccountId IN : accSetId]){
                if(AccountRecMap.containsKey(con.AccountId)){
                con.lastName =  AccountRecMap.get(con.AccountId);    
                }
                
            lstContact.add(con);
            }
            if(lstContact.size() > 0){
                update lstContact;
            }
        }
        
       
    }

}

I hope it will work of your requirment.
let me know if it's helps you and mark the best of this so that it can help to others.
Thank You