You need to sign in to do that
Don't have an account?

Help with trigger to prevent duplicate contacts
I'm trying to implement a trigger to prevent duplicate contacts from being entered. The criteria is that it should prevent the contact from being added if the first and last name and any of the phone numbers match those of an existing contact, or if the email matches an existing contact regardless of whether the name matches or not.
Here's the code I'm trying to get it to accept:
trigger ContactDuplicateTrigger on Contact (before insert) {
for (Contact c : Trigger.new){
Contact[] contacts= [select id from Contact where
(FirstName = :c.FirstName and LastName = :c.LastName) and
(Phone=:c.Phone or MobilePhone=:c.MobilePhone or HomePhone=:c.HomePhone or OtherPhone=:c.OtherPhone or Home_Phone_2__c=:c.Home_Phone_2__c)
or Email = :c.Email];
if (contacts.size() > 0) {
c.LastName.addError('Contact cannot be created - Contact already exists with the same email or name-phone combination.');
}
}
}
Here's the error it gives me:
Error: Compile Error: expecting right square bracket, found 'or' at line 6 column 4 |
I tried adding in parentheses to group the logic correctly, but I wonder if Apex support it. Can someone help me with the syntax to enforce the desired logic?
Thank you!
Hi
Please use the below code there is no error found
trigger ContactDuplicateTrigger on Contact (before insert) {
for (Contact c : Trigger.new){
Contact[] contacts= [select id from Contact where
(FirstName = :c.FirstName and LastName = :c.LastName) and
(Phone=:c.Phone or MobilePhone=:c.MobilePhone or HomePhone=:c.HomePhone or OtherPhone=:c.OtherPhone or Home_Phone_2__c=:c.Home_Phone_2__c
or Email = :c.Email)];
if (contacts.size() > 0) {
c.LastName.addError('Contact cannot be created - Contact already exists with the same email or name-phone combination.');
}
}
}
Only change is remove parenthesis from line 5 and add it to the line 6 end
Thanks
Kannan B
Hi,
Will this keep duplicate contacts from being duplicated? I think this is something I can use, but what error message will display from the user screen?
Nick