You need to sign in to do that
Don't have an account?
Nish321
trigger to check for duplicate email and throw error
Not able to figure out what's wrong with this trigger.
trigger DuplicateEmail on Contact (before insert, before update) { map<string, contact> conmap = new map<string, contact> (); for(contact con : trigger.new) { if(con.email!=null){ conmap.put(con.email, con); } } map<string, contact> emailmap = new map<string, contact> ([select email, id from contact where email IN: conmap.keyset() limit 1]); for(contact c : trigger.new) { if(emailmap.get(c.email) !=null) { c.email.adderror('this is duplicate email'); } } }
Please let us know if this will help you
All Answers
Please let us know if this will help you
Your query at Line #16 will return map which has ID as key instead of Email. If you capture SOQL return data in Map, it will store ID as key and value as sObject. So, emailMap is actually havin Contact Id as key and not the email value. Hence your code at line #27 will not satisfy the criteria. You need to update the code to find a duplicate. There are multiple ways to re-write this code, I am just rewritting the query and duplicate check part of the code.
-Thanks,
TK
Did this answer your question? If not, let me know what didn't work, or if so, please mark it solved.
@Tarun : Thanks again for your detailed explanation to make me understand what was causing the issue.