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-triggerHope this helps you. Please mark this answer as best so that others facing the same issue will find this information useful. Thank you
1 answer