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){


        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) {

Your class is explicitly taking no action if the Primary_Email__c field is populated, which would be the case if you changed an existing value in the Exchange_Contact__c field:

if (oppt.Exchange_Contact__c != null && oppt.Primary_Email__c == null) {

You'll likely want to change this to something like

if (oppt.Exchange_Contact__c != null 
    && mapCont.containsKey(oppt.Exchange_Contact__c) 
    && oppt.Primary_Email__c != mapCont.get(oppt.Exchange_Contact__c).Email) {

so that you take action if and only if a change is required.

That said, this could easily just be a formula field.

  • I kind of was leaning towards a "they allow manual overrides" situation, because otherwise a formula would make sense, but this may be a valid solution, too (p.s. if Exchange_Contact__c != null, the map contains the key). – sfdcfox May 14 '20 at 1:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.