When a contact is updated, i want to know the old value of the owner. This is how I am testing --- Changed Owner on Account, as a result, owner on Contact changed to be the same as Account Owner. The ContactOwner changes as expected however, I am not able to get the value of old ContactOwner.
I am trying to understand why trigger.oldMap gives me the value of new Owner?
trigger ContactTrigger on Contact (before update) {
if (Trigger.isBefore) {
if (Trigger.isInsert) {
ContactTriggerHandler handler = new ContactTriggerHandler(Trigger.new);
handler.beforeInsert();
} else if (Trigger.isUpdate) {
ContactTriggerHandler handler = new ContactTriggerHandler(Trigger.new,Trigger.oldMap,Trigger.newMap);
handler.beforeUpdate();
}
}
}
//**************** Handler Class ***************** //
public with sharing class ContactTriggerHandler {
public List<Contact> contacts;
public Map<Id,Contact> mapIdVsOldContact;
public Map<Id,Contact> mapIdVsNewContact;
public ContactTriggerHandler(List<Contact> triggerNew) {
this.contacts = triggerNew;
}
public ContactTriggerHandler(List<Contact> triggerNew,Map<Id,Contact> mapIdVsOldContact, Map<Id,Contact> mapIdVsNewContact) {
this.contacts = triggerNew;
this.mapIdVsOldContact = mapIdVsOldContact;
this.mapIdVsNewContact = mapIdVsNewContact;
}
public void beforeInsert() {
updateContactOwner();
}
public void beforeUpdate() {
updateContactOwner();
}
public void updateContactOwner() {
Set<Id> accountIds = new Set<Id>();
for (Contact c : contacts) {
if (c.AccountId != null) {
if (!accountIds.contains(c.AccountId)) {
accountIds.add(c.AccountId);
}
}
}
Map<Id,Account> accts = new Map<Id,Account>(
[SELECT OwnerId
FROM Account
WHERE Id in :accountIds]);
for (Contact c : contacts) {
Contact myoldContact = mapIdVsOldContact.get(c.Id);
system.debug('My old Contact Owner is ' +myoldContact.OwnerId); // shows new owner
if (c.AccountId != null && accts.containsKey(c.AccountId)) {
c.OwnerId = accts.get(c.AccountId).OwnerId;
system.debug('My New Contact Owner is ' + c.OwnerId); // shows new owner
}
}
}