Drills › Automate with triggers
React to a Contact email change
Automate with triggers · Intermediate · 15 min · Runs in your Salesforce Developer org · Apex Path
Scenario. An integration team wants to see which Contacts changed Email, without flagging other edits.
Compare each Contact with its saved version in Trigger.oldMap and mark only records whose Email really changed.
What you will learn
An update trigger sees two versions of each record: the new one in Trigger.new and the saved one in Trigger.oldMap, looked up by Id. A before-update trigger saves your changes to Trigger.new for you, so it needs no DML.
Contact oldRow = oldMap.get(newRow.Id);
Boolean phoneChanged = newRow.Phone != oldRow.Phone;
Gotcha. In Apex, == and != on text ignore letter case, so [email protected] and [email protected] count as equal. .equals() does check case.
The task
Complete the handler so a Contact's Description becomes Email changed only when its Email really changes during an update.
Examples:
[email protected]→[email protected]: Description becomesEmail changed- only Phone changes: Description stays as it was
[email protected]→[email protected](letter case only): not a change
Requirements:
- For each new Contact, get its saved version from
oldMapby Id. - Compare the old and new Email with
!=. It also handles null on either side. - Set Description to
Email changedonly when the Email changed. - Do not call
update. This runs in a before-update trigger, so Salesforce saves your change.
Starter code
public class AS_7BE5BEFCF051_ContactChanges {
public static void beforeUpdate(List<Contact> newContacts, Map<Id, Contact> oldMap) {
for (Contact contact : newContacts) {
Contact oldContact = oldMap.get(contact.Id);
}
}
}
When it passes
Only real Email changes, including to or from blank, get the marker. Letter-case-only edits and other field edits leave Description alone, one record or 200.
You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.
‹ Create follow-up Tasks after Contact insert · Route Case trigger contexts ›