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
munna123munna123 

how to update phone field of account obj from contact obj phone field using trigger

hi all...here we need to write a trigger. we need to create a contact on contact object for a particular account. when we give the value in phone field of contact, the phone field of parent account of this contact should get updated with the phone field value given in contact object.
am a beginner so not understanding.
here is my coding

trigger tgr_fieldupdate on Contact (after update) {
   list<contact> ls= [select id,phone from contact];
    contact con= trigger.new[0];
    account acc = new account();
        for(contact c:ls){
            c.phone= acc.phone;
            update acc;
        }
    
Swayam  AroraSwayam Arora
trigger tgr_fieldupdate on Contact (after update) {
	List<Contact> contacts = Trigger.New;	
	Set<Id> accIds = new Set<Id>();

	for(Contact con : contacts) {		
		accIds.add(con.AccountId);
	}
	
	List<Account> accounts = [Select Id, Phone from Account where Id in :accIds];
	
	for(Account acc : accounts) {
		for(Contact con : contacts) {
			if(con.AccountId == acc.Id) {
				acc.Phone = con.Phone;
			}
		}
	}
	update accounts;
}

This is the simple trigger for your requirement. Although it is not following any Best Practise but still works fine.

Please close the thread marking this answer as Best Answer if it really helped. Closing the thread help others finding the correct answer.

Regards,
Swayam Arora
munna123munna123
ya its working.. thnq... is there any other method with four to five line code to do so?
Swayam  AroraSwayam Arora
There is no smaller solution. Solution will be big only but I don't think it is required for your scenario. Why don't you read the Apex Trigger Best Practices and try to modify it yourself. It will be a learning for you.

Please close the thread marking this answer as Best Answer if it really helped. Closing the thread help others finding the correct answer.
munna123munna123
its ok. thnq very much