+ Start a Discussion
Manoj DeshmukhManoj Deshmukh 

write a trigger to update account field whenever contact get inserted or updated

RamakantRamakant
Hi Manoj,

Please try below code:
trigger updateaccount on Contact (after insert, after update) {
    Map<Id, Integer> accountIdAndPhoneMap = New Map<Id, Integer>();
    Set<ID> aID = new Set<ID>();
    List<Account> acclist = new List<Account>(); 
        for(Contact con:Trigger.new)
        {
            if(con.Phone != null){
                aID.add(con.AccountId);
				accountIdAndPhoneMap.put(con.AccountId, con.Phone);
            }
        }
        for(Account a:[select id, Phone, (select id, Phone from contacts) from Account where ID IN: aID])
        {
			a.Phone = accountIdAndPhoneMap.get(a.id);
            acclist.add(a);
        }
        update acclist;    
}

PLease let me know if helped.

Regards,
Ramakant
goabhigogoabhigo
Why do you need trigger? The same can be done using Workflow field update or Process Builder.
Manoj DeshmukhManoj Deshmukh
Thnx Ramakant 
Is there any way to implement this trigger without using map. 
Manoj DeshmukhManoj Deshmukh
Is it possible only using List and Set to implement this Trigger
David @ ConfigeroDavid @ Configero
Why would you want to _not_ use a map?  You would be using bad development patterns and over complicating code.  You also risk creating runtime errors by attempting to update an Account multiple times if you use a list of Accounts.  A Map of Accounts by Account Id, like a Set, is a good design practice to deduplicate values when used correctly.