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
VICKY_SFDCVICKY_SFDC 

Duplicate Contact based on phone and email

Whenever m insert a contact or  list of contact, same email and phone number popup an error of duplicate error
       Based on contact email and phone?
 
Best Answer chosen by VICKY_SFDC
ShirishaShirisha (Salesforce Developers) 
Hey Vikas,

Please find the Trigger code in the below blog which will throw the error whenever the Contact with the same Phone and Email is already exists.

https://www.syedtaha.com/salesforce-apex-triggers/salesforce-apex-trigger-to-prevent-duplicate-contacts-by-email-or-phone-number/897/#:~:text=1.,before%20the%20Contact%20is%20created.

Kindly mark it as best answer if it helps so that it can help others in the future.

Warm Regards,
Shirisha Pathuri

 

All Answers

ShirishaShirisha (Salesforce Developers) 
Hi Vikas,

Greetings!

Please check,if you have any duplicate rules created based on the Email and Phone number on Contact Object.

In order to check the duplicate rules please go to Setup, use the Quick Find box to find Duplicate Rules.

Reference:https://help.salesforce.com/articleView?id=duplicate_rules_create.htm&type=5

Kindly mark it as best answer if it helps so that it can help others in the future.

Warm Regards,
Shirisha Pathuri
VICKY_SFDCVICKY_SFDC
@Shirisha Thanks For reply,,Actully They Specially Want to Achieve this usng Apex Trigger
ShirishaShirisha (Salesforce Developers) 
Hey Vikas,

Please find the Trigger code in the below blog which will throw the error whenever the Contact with the same Phone and Email is already exists.

https://www.syedtaha.com/salesforce-apex-triggers/salesforce-apex-trigger-to-prevent-duplicate-contacts-by-email-or-phone-number/897/#:~:text=1.,before%20the%20Contact%20is%20created.

Kindly mark it as best answer if it helps so that it can help others in the future.

Warm Regards,
Shirisha Pathuri

 
This was selected as the best answer
VICKY_SFDCVICKY_SFDC
trigger PreventDuplicateContacts on Contact (before insert) {
// Set to store email ids
Set <String> emailSet = new Set<String>(); 
// Set to store phone numbers
Set <String> phoneSet = 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);
phoneSet.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 :emailSet OR phone IN :phoneSet];
// 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.' );
}
}
}