Whenever account’s phone field is updated then all related contact’s phone field should also get updated with the parent account’s phone

Trigger

trigger AccountTrigger on Account (after update) {
    if (Trigger.isAfter && Trigger.isUpdate) {
        UpdateContactPhoneHandler.handleUpdate(Trigger.newMap, Trigger.oldMap);
    }
}

Apex Class

public class AccountTriggerHandler {
	public static void updatePhoneField(Map newAccMap, Map oldAccMap) {
        
      	set accIds = new Set();
        List contactToBeUpdate = new List();
        
        for(Account acc: newAccMap.values()) {
            if(acc.Phone != oldAccMap.get(acc.Id).Phone) {
                accIds.add(acc.Id);
            }
        }
        
        if (!accIds.isEmpty()) {
            List conList = [SELECT Id, Phone, AccountId 
                                     FROM Contact 
                                     WHERE AccountId IN: accIds];
            
            if(!conList.isEmpty()) {
                for(Contact con: conList) {
                    con.Phone =  newAccMap.get(con.AccountId).Phone;
                    contactToBeUpdate.add(con);
                }   
            }
        }
        
        if(!contactToBeUpdate.isEmpty()) {
            update contactToBeUpdate;
        }
    }
}

Apex Test Class

@isTest
private class AccountTriggerHandlerTest {
    @isTest
    static void testContactPhoneUpdate() {
        // Create test data
        Account acc = new Account(Name = 'Test Account', Phone = '123-456-7890');
        insert acc;
        
        Contact con = new Contact(FirstName = 'Test', LastName = 'Contact', AccountId = acc.Id);
        insert con;
        
        // Update the Account's phone number
        acc.Phone = '987-654-3210';
        update acc;
        
        // Retrieve the updated contact
        Contact updatedCon = [SELECT Id, Phone FROM Contact WHERE Id = :con.Id];
        
        // Assert that the contact's phone field got updated
        System.assertEquals(acc.Phone, updatedCon.Phone);
    }
}

Leave a Comment

Your email address will not be published. Required fields are marked *