Prevent Duplicate Contact Creation by Email

This trigger ensures that Contact records with duplicate Email, Last Name, and Phone values are not created. It validates existing records and throws an error if duplicates are found.

For hands-on practice, check this YouTube playlist.

Solution:

public class ContactTriggerHandler {
                public static void handleBeforeInsert (List<Contact> newRecords) {
                            List<Contact> existingRecords = [SELECT Id, LastName, Phone, Email FROM
                            Contact LIMIT 50000];

                           for (Contact con: newRecords) {
                               for (Contact existingCon : existingRecords) {
                                      if (con.LastName == existingCon.LastName && con.Email == existingCon.
                                      Email && con.Phone == existingCon.Phone){
                                               con.addError(‘Duplicate Found’);
                                       }
                                }
                       }
            }
}

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 :)