function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Asel Vazir 1Asel Vazir 1 

trigger handler populating Contact email address on Opportunity custom field Primary_Email__c doesn't change the email when updating the Contact

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;

Here is the Trigger:
trigger populatePrimaryEmailOnExchange on Opportunity (before insert, before update, after update) {

    if (Trigger.isBefore || Trigger.isInsert || Trigger.isUpdate) {

Agustin BAgustin B
Hi asel, thats because you are asking "oppt.Primary_Email__c == null" in line 18, so if you already had a value there, then is never going to enter that condition and update the email and contact id.

if it helps please mark as best answer, it may help others.
Derrick AbbeyDerrick Abbey
Hi Asel,

This seems like it would be much easier to handle with a formula field.  Is there a reason you're not just using one of those?