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
mohammed kingmohammed king 

fin tri

write a trigger to prevent duplicate contact with email on selected account trigger should throw exception  and also when duplicate contact is inserted ext
Deepali KulshresthaDeepali Kulshrestha
Hi mohammed,

This apex trigger prevents the user from creating duplicate contacts when a contact already exists with the same Email
trigger PreventDuplicateContacts on Contact (before insert) {
    
    // Set to store email ids
    Set <String> emailSet = new Set<String>(); 
    
    // Iterate through each Contact and add their email and phone number to their respective Sets
    for (contact con:trigger.new) {
        emailSet.add(con.email);
    }
 
    // 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 :emailSet];
 
    // 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
            con.email.adderror( 'Duplicate Contact Found. Use Existing Contact.' );
        }
    }
 
}

I suggest to visit this link, it will help you

https://www.syedtaha.com/salesforce-apex-triggers/salesforce-apex-trigger-to-prevent-duplicate-contacts-by-email-or-phone-number/897/

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha.