• ankit dangre
  • NEWBIE
  • 10 Points
  • Member since 2021

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 2
    Questions
  • 0
    Replies
trigger UpdateAccountPhoneBasedOnContact on Contact (after insert,after update) {
    set<id> setAccid=new set<id>();
    map<id,Account>mapAcc=new map <id,Account>();
    for(contact con:trigger.new){
        if(trigger.isInsert && con.AccountId!=null && con.phone!=null){
            setAccid.add(con.AccountId);
        }
        if(trigger.isUpdate && con.AccountId!=null && con.phone!=trigger.oldMap.get(con.Id).phone){
            setAccid.add(con.AccountId);
        }
    }
    if(!setAccid.isEmpty()){
        for(account acc:[select id,name,phone from account where id in:setAccid]){
            mapAcc.put(acc.id,acc);
        }
    }
    list<account> updateAcclist=new list<account>();
    if(!mapAcc.isEmpty()){
        for(contact con:trigger.new){
            if(mapAcc.containsKey(con.AccountId)){
                mapAcc.get(con.AccountId).phone=con.Phone;
                updateAcclist.addAll(mapAcc.values());
            }
        }
    }
}