Apex Trigger: Update Contacts records following Account Name changes

Salesforce apex test Update Contacts records following Account Name changes

We want a trigger that updates all related Contacts when an Account’s Name is changed. For example:
If an Account’s Name changes, all Contacts associated with that Account should have their Account Name field updated to reflect the change. In addition to that, the trigger is updating the Title field of each record that this trigger has modified.

Here is the Apex Trigger code we should implement:

trigger UpdateContactsOnAccountChange on Account (after update) {
    // List to hold Contacts to be updated
    List<Contact> contactsToUpdate = new List<Contact>();

    // Loop through updated Accounts
    for (Account acc : Trigger.new) {
        // Get the old Account values
        Account oldAcc = Trigger.oldMap.get(acc.Id);

        // Check if the Account Name has changed
        if (acc.Name != oldAcc.Name) {
            // Query related Contacts
            List<Contact> relatedContacts = [SELECT Id, Title FROM Contact WHERE AccountId = :acc.Id];
            for (Contact con : relatedContacts) {
                // Update Contact Title
                con.Title = 'Updated due to Account Name Change';
                contactsToUpdate.add(con);
            }
        }
    }

    // Perform the update if there are Contacts to update
    if (!contactsToUpdate.isEmpty()) {
        update contactsToUpdate;
    }
}

In order to update this code, you should navigate to the Developers Console, click on New and choose Apex Trigger. Name it UpdateContactsOnAccountChange and paste the code provided above. Save the changes. By this, the trigger should be working.

Check if the trigger is active

We can have an additional check if the trigger is actually active by following these steps:
Go to Setup
Search for “Apex Triggers” in the Quick Find box
Click on Apex Triggers.
Find the Trigger: Locate the trigger you want to check in the list.
Edit the Trigger:
Click on the trigger name.
Click the Edit button.
Check if the “Is Active” checkbox is checked or not. If you want it to be active, it should be checked, while if you want to deactivate this trigger, then you have to uncheck it and save the changes.

Let’s manually test if the trigger is working as expected

The trigger code given above should apply on all items listed in the Accounts object. Still, for testing purposes let’s create our own item. Let’s name it “Test Account”.

Following this, we should create a contact item that will use “Test Account” as the Account Name. Now, what the trigger above actually does is that, for example, if we change the value of the Account Name in the Accounts object, this Account Name value should change to the matching value for all items in the Contacts object that are related to that Account Name. For testing purposes let’s create an item with the name of Donald Trump, and for the Account Name let’s choose “Test Account” from the list, the one we have just created.

So let’s suppose that we are changing the “Test Account” value to “Updated Test Account” in the Accounts object. When we save the changes the trigger should automatically update this value for the Donald Trump item in the Contacts object. If that’s the case, it means that our trigger works fine.

We can additionally check this by deactivating the trigger. This time, changes on the Account Name in the Accounts object shouldn’t reflect on the Contacts object.

Let’s do some Apex Class testing

Here is the Apex test that we can run in order to see if the trigger has been successfully implemented:

@isTest
public class UpdateContactsOnAccountNameChangeTest {
    @isTest
    static void testTrigger() {
        // Step 1: Create an Account
        Account testAccount = new Account(Name = 'Initial Name');
        insert testAccount;

        // Step 2: Create Contacts linked to the Account
        Contact testContact1 = new Contact(
            FirstName = 'John',
            LastName = 'Doe',
            Title = 'Original Title',
            AccountId = testAccount.Id
        );
        Contact testContact2 = new Contact(
            FirstName = 'Jane',
            LastName = 'Smith',
            Title = 'Original Title',
            AccountId = testAccount.Id
        );
        insert new List<Contact>{testContact1, testContact2};

        // Step 3: Update the Account Name
        testAccount.Name = 'Updated Name';
        update testAccount;

        // Step 4: Verify that the Account Name is updated
        Account retrievedAccount = [SELECT Id, Name FROM Account WHERE Id = :testAccount.Id];
        System.assertEquals('Updated Name', retrievedAccount.Name, 'Account Name should be updated.');

        // Step 5: Verify that Contacts were updated
        List<Contact> updatedContacts = [SELECT Title FROM Contact WHERE AccountId = :testAccount.Id];
        for (Contact con : updatedContacts) {
            System.assertEquals('Updated due to Account Name Change', con.Title, 'Contact Title should be updated.');
        }
    }
}


Scroll to Top