Prevent Duplicate Contacts by Email

This trigger ensures no duplicate Contact records are created by checking for existing Contacts with the same email address. Users receive an error if a duplicate is detected.

For hands-on practice, visit this YouTube playlist.

Solution:

public static void preventDuplicateEmail(List<Contact>
conList,Map<Contact> oldMap){
                Set<String> emailSet= new Set<String>();
                for(Contact con:conList){ if(oldMap==null
                && con.Email!=null){
                emailSet.add(con.Email);
                            }else{ if(con.Email!=null &&
                                            con.Email!=oldMap.get(con.Id).Email){
                                            emailSet.add(con.Email);
                            }
            }
}
        List<Contact> existingContactList= new List<Contact>([SELECT Id,Email
        FROM Contact WHERE Email IN:emailSet]);
        Set emailListForExisting= new
        Set<String>(); if(!existingContactList.isempty()){
        for(Contact con:existingContactList){
        emailListForExisting.add(con.Email);
                  }
}
         for(Contact con:conList){
                    if(emailListForExisting.contains(con.Email)){
                    con.addError(‘Duplicate email’);
                   }
}
}

Want to Apply As Content Writer?

Leave a Comment

Your email address will not be published. Required fields are marked *

Shopping Cart

Let's get you started!

Interested in writing Salesforce Content?

Fill in this form and we will get in touch with you :)