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


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.