The below code works fine when I insert a new Contact with email. But when I update the Exchange Contact field on Opportunity it still keeps the email of the previous Contact. Please help me to resolve the issue.
public with sharing class PrimaryEmailOnExchange {
public static void populatePrimaryEmailOnExchange(List<Opportunity> oppList) {
Set<Id> conIds = new Set<Id>();
for (Opportunity oppt : oppList) {
if(oppt.Exchange_Contact__c != null){
conIds.add(oppt.Exchange_Contact__c);
}
}
Map<Id, Contact> mapCont = new Map<Id, Contact>([
SELECT Id, Email FROM Contact WHERE Id IN : conIds
]);
for (Opportunity oppt : oppList) {
if (oppt.Exchange_Contact__c != null && oppt.Primary_Email__c == null) {
if (mapCont.containsKey(oppt.Exchange_Contact__c)) {
Contact c = mapCont.get(oppt.Exchange_Contact__c);
oppt.Primary_Email__c = c.Email;
oppt.ContactId = c.Id;
}
}
}
}
}
And Trigger:
trigger populatePrimaryEmailOnExchange on Opportunity (before insert, before update, after update) {
if (Trigger.isBefore || Trigger.isInsert || Trigger.isUpdate) {
PrimaryEmailOnExchange.populatePrimaryEmailOnExchange(Trigger.new);
}
}