Trigger – Update All Account Related Contacts

Trigger to update account related contacts
Trigger to update account related contacts

Here is apex trigger to update account related contacts when Email of account is updated. We have created a new custom fields on account named as email and if email got updated we want to set that email to all the associated contacts.

				
					trigger AccountTrigger2 on Account(after update) {

    Set < Id > accountIdSet = new Set < Id > ();

    for (Id accountId: Trigger.NewMap.keySet()) {
        if (Trigger.OldMap.get(accountId).Email__c != Trigger.NewMap.get(accountId).Email__c) {
            accountIdSet.add(accountId);
        }
    }

    List < Contact > lstContact = [SELECT id, Email, AccountId FROM Contact where      AccountId In: accountIdSet];

    List < Contact > contactToUpdate = new List < Contact > ();
    for (Contact con: lstContact) {
        Contact contact = new Contact(Id = con.Id);
        contact.Email = Trigger.NewMap.get(con.AccountId).Email__c;
        contactToUpdate.add(contact);

    }
    if (!contactToUpdate.isEmpty()) {
        update contactToUpdate;
    }
}
				
			

In this video we have discussed the trigger in detail.

Leave a Reply