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
raju p 4raju p 4 

I have little dought in trigger can we update account phone number by contact phone number >ON Beffore update,,please focus on this, i am using map i am not getting need know for learning purpose

I have little dought in trigger  can we update account phone number by contact phone number >ON Beffore update,,please focus on this, i am using map i am not getting need know for learning purpose 
 i know after it is possible please brifly explain me,

// update AccountPHONE by CONTACT
   public Class BeoreupdateAccountPhone{
       public static void beforeupdate(map<id,contact>newmap,map<id,contact>oldmap){
       
        set<id> ids= new set<id>();
       for(id key:oldmap.keyset()){
         contact n1= newmap.get(key);
         contact o1= oldmap.get(key);
             ids.add(key);
             
             list<account> ac= new list<account>();
             list<account> acc=[select phone,(select phone from contacts) from account where id=:ids];
                 for(account a:acc){
                    for(contact c:a.contacts){
                       if(a.phone!= c.phone){
                       a.phone= c.phone;
                           //acc.add((c.phone).contacts);
                           }
                           }
                       }
                       update acc;
                       }
                         }}
Gurpreet Singh PanesarGurpreet Singh Panesar
Hello Raju,
trigger AccountPhone on Contact (after Insert, before Update) {
    
    List<Account> accListUpdate = new List<Account>();
    
    Map<Id,String> accPhoneMap = new Map<Id,String>();

        for(Contact con:Trigger.New) {
            accPhoneMap.put(con.AccountId,con.Phone);  
            System.debug('here'+accPhoneMap);   
        }
        
        List<Account> accList = [Select ID,Phone FROM Account WHERE ID IN : accPhoneMap.keySet()];
            
        for(Account acc : accList) {
            
            acc.Phone = accPhoneMap.get(acc.Id);
            accListUpdate.add(acc);
            System.debug('inside for'+accListUpdate);
        }               
        if(accListUpdate.size()>0) {
            update accListUpdate;
        }
}


I have posted you a logic which will work on After Insert and Before Update, you should copy and paste this logic without modifying in your org and will work as your requirement.
It will update Account Phone which is updated on Contact.
Thanks,
Raju