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
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.
- The trigger is executed on the
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.
- The trigger compares the old value (
Bulk Processing:
- The trigger is bulkified, meaning it can handle updates to multiple Account records in a single transaction.