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
himanshu huske 7himanshu huske 7 

New Task

Help Me With Simple Code.
 Whenever  a new contact is created for account, update the  corresponding account phone with the new contact phone field.
Best Answer chosen by himanshu huske 7
abhishek singh 497abhishek singh 497
Hello Himashu,
Below is the code for your requirements,

trigger UpdateAccountField on Contact (after insert) {
    Map<ID,Account> contactAccountMap = new Map<ID,Account>();
    Set<Id> accountIdSet = new Set<Id>();
    for(Contact con : trigger.new){
        if(con.AccountId!=null && con.Phone!=null){
            accountIdSet.add(con.AccountId); 
        }
    }
    contactAccountMap = new Map<ID,Account>([SELECT id,Phone,(SELECT id,Phone FROM Contacts) FROM Account WHERE ID IN:accountIdSet]);
    System.debug('value in contactAccountMap===>'+contactAccountMap);
    for(Contact con : trigger.new){
        Account myNewAccount = contactAccountMap.get(con.AccountId);
        myNewAccount.Phone = con.Phone; 
    }
    update contactAccountMap.values();
}

I have tested in my org and it's working fine.
Please let me know your queries.
I you find it helpful ,Please mark it as a best answer.

Thank You,
Abhishek Singh.