Search Here

If the Account phone is updated then populate the phone num triggers in Salesforce

 To populate the Phone number field or update another field when the Account Phone is updated in Salesforce, you can create an Apex Trigger that detects changes to the Phone field and then updates the relevant field accordingly.

Here’s an example of how to create an Apex Trigger that updates a custom field (e.g., Phone_Num__c) with the new phone number when the Phone field is updated:

trigger UpdatePhoneNumOnPhoneChange on Account (before update) {

    // Loop through the Account records being updated

    for (Account acc : Trigger.new) {

        // Check if the Phone field has changed (compare old and new values)

        if (acc.Phone != Trigger.oldMap.get(acc.Id).Phone) {

            // Set the custom Phone_Num__c field with the updated phone number

            acc.Phone_Num__c = acc.Phone;

        }

    }

}

Explanation of the Code

  1. Trigger Event:

    • The trigger is executed on the before update event. This allows you to modify the Phone_Num__c field before the Account record is saved to the database.
  2. Logic:

    • The trigger compares the old value (Trigger.oldMap.get(acc.Id).Phone) and the new value (acc.Phone) of the Phone field.
    • If the Phone field has been updated, the trigger sets the Phone_Num__c field to the new value of Phone.
  3. Bulk Processing:

    • The trigger is bulkified, meaning it can handle updates to multiple Account records in a single transaction.
@isTest
private class UpdatePhoneNumOnPhoneChangeTest {
    @isTest
    static void testPhoneNumUpdate() {
        // Create a test Account with a phone number
        Account testAccount = new Account(
            Name = 'Test Account',
            Phone = '123-456-7890'
        );
        insert testAccount;

        // Update the Phone number of the Account
        testAccount.Phone = '987-654-3210';
        update testAccount;

        // Query the Account to verify that the Phone_Num__c field has been updated
        Account updatedAccount = [SELECT Phone, Phone_Num__c FROM Account WHERE Id = :testAccount.Id];

        // Assert that the custom Phone_Num__c field matches the updated Phone number
        System.assertEquals('987-654-3210', updatedAccount.Phone_Num__c, 'Phone_Num__c should match the updated Phone number');
    }
}




Tags

Post a Comment

0 Comments
* Please Don't Spam Here. All the Comments are Reviewed by Admin.