/*This code is check Duplicate Emil, if in the records email already exits and again you want to enter same email id then it prevent to save record and show Email Already Exits Error Message */
trigger duplicate_Email_Check on Contact (before insert, before update) {
set<String> emailAdd = new set<String>();
for(Contact con : Trigger.New){
emailAdd.add(con.Email);
}
List<Contact> conList = [SELECT id, Email FROM Contact where Email IN : emailAdd];
if(Trigger.isUpdate){
for(Contact con : Trigger.New){
if(con.Email!=null && conList.size()>0 && Trigger.oldmap.get(con.id).Email!=con.Email) {
con.Email.addError('Email AlReady Exits');
}
}
}
if(Trigger.isInsert){
for(Contact con : Trigger.New){
if(con.Email!=null && conList.size()>0) {
con.Email.addError('Email AlReady Exits');
}
}
}
}
//******************************************************************************//
//If You want to Undelete Event also here is code
trigger duplicate_Email_Check on Contact (after undelete, before insert, before update) {
Set<String> emailAdd = new Set<String>();
Integer contactThreshHold;
Map<String, Integer> emailToNoOfContactsMap = new Map<String, Integer>();
for(Contact con : Trigger.New){
emailAdd.add(con.Email);
}
for(Contact existingContact : [SELECT id, Email FROM Contact where Email IN : emailAdd]) {
if(!emailToNoOfContactsMap.containsKey(existingContact.Email)) {
emailToNoOfContactsMap.put(existingContact.Email, 0);
}
Integer emailRelatedContactCount = emailToNoOfContactsMap.get(existingContact.Email);
emailRelatedContactCount = emailRelatedContactCount + 1;
emailToNoOfContactsMap.put(existingContact.Email, emailRelatedContactCount);
}
private void checkDuplicateEmail(List<Contact> contactsList, Integer conThreshHold) {
for(Contact con : contactsList){
if(con.Email!=null && emailToNoOfContactsMap.get(con.Email) > conThreshHold) {
con.Email.addError('Email already Exits');
}
}
}
if(Trigger.isInsert ) {
checkDuplicateEmail(Trigger.New, 0);
}
if(Trigger.isUpdate ) {
checkDuplicateEmail(Trigger.New, 0);
}
if(Trigger.isUnDelete) {
checkDuplicateEmail(Trigger.New, 1);
}
}
No comments:
Post a Comment