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
Vincent Drader 2Vincent Drader 2 

Challenge: De-duping trigger for email across fields

Hello Developers - I am a SF user who is just beginning at coding. I am having trouble with making a trigger that will act as a dupe blocking rule and throw an error whenever a user tries to add a contact whose email matches the Email field OR our custom Other_Email_c field. Right now SF's Data.com Dupe management won't block dupes with a cross-field logic like this, so I turn to coding...but am not sure what this entails. Also would want to build in code that says do not fire trigger if user's profile = ______. Any ideas?
Abhishek BansalAbhishek Bansal
Hi Vincent,

Please use the below trigger to avoid duplicate Email contacts to be inserted or updated in the system :
trigger checkDuplicateEmail on Contact(before insert, before update){
	Set<String> emailIds = new Set<String>();
	for(Contact con : [Select Email, Other_Email_c from Contact where Id Not In :trigger.new]){
		if(con.Email != null){
			emailIds.add(con.Email);
		}
		if(con.Other_Email_c != null){
			emailIds.add(con.Other_Email_c);
		}
	}
	
	for(Contact newContact : trigger.new){
		if(emailIds.contains(newContact.Email)){
			newContact.addError('Contact with this Email Id already exists');
		}
	}
}
If you want that the above trigger should not execute for certain profiles than you must use below code :
trigger checkDuplicateEmail on Contact(before insert, before update){
	User currentUser = [Select Profile.Name from User where Id =: UserInfo.getUserId()];
	String profileName = currentUser.Profile.Name;
		if(profileName != 'Your Profile Name For Which You Want To Exclude this Trigger'){
		Set<String> emailIds = new Set<String>();
		for(Contact con : [Select Email, Other_Email_c from Contact where Id Not In :trigger.new]){
			if(con.Email != null){
				emailIds.add(con.Email);
			}
			if(con.Other_Email_c != null){
				emailIds.add(con.Other_Email_c);
			}
		}
		
		for(Contact newContact : trigger.new){
			if(emailIds.contains(newContact.Email)){
				newContact.addError('Contact with this Email Id already exists');
			}
		}
	}
}


Let me know if you have any issue with the trigger code or if you need any help on this.

Thanks,
Abhishek

Vincent Drader 2Vincent Drader 2
Abhishek! You the man! Giving me code to use - thank you! I'll let you know how it goes.

Vince
Vincent Drader 2Vincent Drader 2
@Abhishek - I have this code now edited, and I am trying to test it to bring it into production. I have gotten it to 58% (7 of 12). Below is what I currently have. Any suggestions to bring the % up?

User-added image