How to prevent duplicate contact

Below code will help to prevent to duplicate contacts based on Email or Phone Number. If contact is already exist then user will face error Message ” Duplicate contact found with phone/email. “

trigger PreventDuplicateContact on Contact (before insert) {
    
    // Set to store email ids
    Set <String> emailList = new Set<String>(); 
    // Set to store phone numbers
    Set <String> phoneList = new Set<String>(); 
    
    // Iterate through each Contact and add their email and phone number to their respective List
    for (contact con:trigger.new) {
        emailList.add(con.email);
        phoneList.add(con.phone);
    }

    // New list to store the found email or phone numbers
    List <Contact> contactList = new List<Contact>();

    // Populating the list using SOQL
    contactlist = [SELECT email,phone FROM Contact WHERE email IN :emailList OR phone IN :phoneList];

    // Iterating through each Contact record to see if the same email or phone was found
    for (contact con:trigger.new) {
        If (contactList.size() > 0) {
            // Displaying the error message
            con.adderror( 'Duplicate contact found with phone/email.' );
        }
    }

}

Leave a Reply