To update the Description field of an Account record whenever the Phone field is updated, you can create an Apex Trigger on the Account object. This trigger will compare the old and new values of the Phone field and populate the Description field with the required message if the Phone field is updated.
trigger UpdateDescriptionOnPhoneChange on Account (before update) {
// Loop through the updated Account records
for (Account acc : Trigger.new) {
// Check if the Phone field has been changed (comparing old and new values)
if (acc.Phone != Trigger.oldMap.get(acc.Id).Phone) {
// Construct the message with the old and new Phone values
String oldPhone = Trigger.oldMap.get(acc.Id).Phone;
String newPhone = acc.Phone;
// Set the Description field with the appropriate message
acc.Description = 'Phone is Updated! Old Value: ' + oldPhone + ' & New Value: ' + newPhone;
}
}
}
Explanation of the Code
Trigger Event:
- This trigger runs on the
before update
event, so it will trigger before the Account record is saved when the Phone field is updated. - Using the
before
update event allows us to modify the Description field before the record is saved.
- This trigger runs on the
Logic:
- The trigger checks if the Phone field value has changed by comparing the current value (
Trigger.new
) with the previous value (Trigger.oldMap
). - If the Phone field is updated, the trigger constructs a message with the old and new Phone values and populates the Description field with the message.
- The trigger checks if the Phone field value has changed by comparing the current value (
Old and New Values:
Trigger.oldMap.get(acc.Id).Phone
fetches the Phone value before the update (old value).acc.Phone
fetches the updated Phone value (new value).
Message Format:
- The message is constructed as:
"Phone is Updated! Old Value: XXX & New Value: XXX"
, whereXXX
represents the old and new Phone values.