Trigger 2 - Whenever a Contact's description is updated, then its Parent Account's description should also get updated by it.

 Whenever a Contact's description is updated, then its Parent Account's description should also get updated by it.




trigger AccountTrigger on Account (after update) {

    if (Trigger.isAfter && Trigger.isUpdate) {

        AccountTriggerHandler.handleAfterUpdate(Trigger.new, Trigger.oldMap);

    }

}





public with sharing class AccountTriggerHandler {

    

    public static void handleAfterUpdate(List<Account> newAccounts, Map<Id, Account> oldAccountMap) {

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

        

        // Loop 1: Find parent accounts where the target field actually changed

        for (Account newAcc : newAccounts) {

            Account oldAcc = oldAccountMap.get(newAcc.Id);

            

            // Explicitly filter updates so execution skips unrelated field updates

            if (newAcc.Phone != oldAcc.Phone) {

                accountIdsWithUpdatedPhone.add(newAcc.Id);

            }

        }

        

        // Exit early if the monitored context data wasn't changed

        if (accountIdsWithUpdatedPhone.isEmpty()) return;

        

        // SINGLE SOQL QUERY: Fetch child contacts corresponding to updated parents

        List<Contact> contactsToUpdate = [

            SELECT Id, Phone, AccountId 

            FROM Contact 

            WHERE AccountId IN :accountIdsWithUpdatedPhone

        ];

        

        if (contactsToUpdate.isEmpty()) return;

        

        // Map the parent contextual data to reference inside our loop structure

        Map<Id, Account> newAccountMap = new Map<Id, Account>(newAccounts);

        

        // Loop 2: Synchronize child records with the parent values in memory

        for (Contact con : contactsToUpdate) {

            Account parentAcc = newAccountMap.get(con.AccountId);

            if (parentAcc != null) {

                con.Phone = parentAcc.Phone;

            }

        }

        

        // SINGLE DML: Safe bulk DML placed entirely outside the loop blocks

        update contactsToUpdate;

    }

}


Comments

Popular posts from this blog

Multi currency in Salesforce - Revenue Cloud Advance - Revenue Lifecycle Management

How to get sessionid and salesforce org base url in salesforce