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

Issue with trigger.
I am writing a trigger which will check and prevent creation of duplicate contatcs.
It's working fine for email but it's not checking Name .
trigger toCheckDuplicateRecord on Contact(before update,before insert) {
List<Contact> Contactlst= new List<Contact>();
Contactlst= [select Name,Email from Contact];
for(Contact conobj:Contactlst)
{
for(Contact con:trigger.new){
if(conobj.Email==con.Email || conobj.Name==con.Name)
con.adderror('You can not enter this contact');
}
}
}
Please suggest.
It's working fine for email but it's not checking Name .
trigger toCheckDuplicateRecord on Contact(before update,before insert) {
List<Contact> Contactlst= new List<Contact>();
Contactlst= [select Name,Email from Contact];
for(Contact conobj:Contactlst)
{
for(Contact con:trigger.new){
if(conobj.Email==con.Email || conobj.Name==con.Name)
con.adderror('You can not enter this contact');
}
}
}
Please suggest.
yuo need ot bulkify your code. Also you cannot query all the contacts, you might hit the SOQL limit. Try the following code
Since Name is the combination of FirstName and LastName, so this cannot be retrieved in before insert event. Use below mentioned line to obtain the name of trigger.new contacts and then do comparison:
String conName = con.FirstName!=NULL ? con.FirstName.trim()+' '+con.LastName.trim() : con.LastName;
I got below eeror when I used the same code-
Compile Error: unexpected token: Map at line 1 column 0
I modified my trigger as belkow and it works fine now-
trigger toCheckDuplicateRecord on Contact(before insert) {
List<Contact> Contactlst= new List<Contact>();
Contactlst= [select LastName,Email from Contact];
for(Contact conobj:Contactlst)
{
for(Contact con:trigger.new){
if((conobj.Email==con.Email && con.email!=NULL)||conobj.LastName==con.LastName ){
con.adderror('You can not enter this contact');
}
}
}
}
1. your trigger needs to handle update as well as insert.
2. You cannot query all of the contacts in your org, once you push it to production it will break.
3. Was you requirement that 2 contacts can't have the same lastname or they can't have the same full name? right now you are onyl checking lastname.
Try the code i posted in my previous reply. It should work for oyu