Trigger 1 - Whenever Account's Phone field is updated, all related Contacts' Phone field should also be updated with the parent Account's Phone.

 Whenever Account's Phone field is updated, all related Contacts' Phone field should also be updated with the parent Account's Phone.



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: Identify accounts where the Phone field actually changed

        for (Account newAcc : newAccounts) {

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

            

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

                accountIdsWithUpdatedPhone.add(newAcc.Id);

            }

        }

        

        // Prevent unnecessary queries if no Phone fields were updated

        if (accountIdsWithUpdatedPhone.isEmpty()) return;

        

        // SINGLE SOQL QUERY: Get all related contacts for the modified accounts

        List<Contact> contactsToUpdate = [

            SELECT Id, Phone, AccountId 

            FROM Contact 

            WHERE AccountId IN :accountIdsWithUpdatedPhone

        ];

        

        if (contactsToUpdate.isEmpty()) return;

        

        // Loop 2: Sync the child Contact's Phone with the parent Account's Phone

        // Using Trigger.newMap (passed indirectly via oldAccountMap's keys/Account context) 

        // to map the new Phone value back down.

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

        

        for (Contact con : contactsToUpdate) {

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

            if (parentAcc != null) {

                con.Phone = parentAcc.Phone;

            }

        }

        

        // SINGLE DML: Update all modified contact records at once

        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