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
Money Care 7Money Care 7 

How to update account field based on contact field

Hi Guys
How to update account field when i am updating contact field uisng trigger.

For expamle:

account and contact object have mail _id__c custom field if i will update contact mail_id__c field then that will be updated in account object automatically..
veda shriveda shri
Hi Money,

Please try below trigger and its handler code:
 
trigger ContactTrigger on Contact (after Update) {
  ContactTriggerHandler objCont = new ContactTriggerHandler();
  
  if(trigger.isInsert && trigger.isUpdate)
	{
		objCont.onAfterUpdate(trigger.new, trigger.OldMap);
	}
 }

Handler
 
Public class ContactTriggerHandler
{
	public ContactTriggerHandler()
	{
	
	}
	
	public void onAfterUpdate(List<Contact> lstNewCon, map<Id,Contact> mapOldCon )
	{
		List<Account> lstAccpuntToUpdate = new List<Account>();
		set<Id> setAlreadyAddedAccId = new set<Id>();
		for(Contact objCont : lstNewCon)
		{
			if(objCont.AccountId != null && String.isNotBlank(objCont.mail_id__c)  && objCont.mail_id__c != mapOldCon.get(objCont.Id).mail_id__c && !setAlreadyAddedAccId.contains(objCont.AccountId))
			{
				lstAccpuntToUpdate.add(new Account(Id = objCont.AccountId,  mail_id__c = objCont.mail_id__c))
			}
		}
		
		if(!lstAccpuntToUpdate.isEmpty())
			update lstAccpuntToUpdate;
	}
}