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
Priya 777Priya 777 

contact duplicate trigger

​Hi For this trigger will it be possible it through following way .please let me know  

trigger ContactDuplicatePreventer on Contact (before insert, before update) {
    Map<String, Contact> ConMap = new Map<String, Contact>();
        for (Contact Contact : System.Trigger.new) {
      
               if ((Contact.Email != null) &&
                (System.Trigger.isInsert ||
                (Contact.Email !=
                    System.Trigger.oldMap.get(Contact.Id).Email))) {
       
   
            if (ConMap.containsKey(Contact.Email)) {
                Contact.Email.addError('Another Contact has the same email address.');
            } else {
                ConMap.put(Contact.Email, Contact);
            }
       }
    }
   
    for (Contact Contact : [SELECT Email FROM Contact
                      WHERE Email IN : ConMap.KeySet()]) {
        Contact newContact = ConMap.get(Contact.Email);
        newContact.Email.addError('A Contact with this E-mail address already exists.');
    }
}

Hi For this trigger will it be possible it through following way .please let me know  

Suppose i have alredy existing User contact with Email address xyz@gmail.com which is active 
If i try to create the 2 nd User with same email address xyz@gmail.com it will through error that email already exists because the first user  is active.

I want to make my trigger to work like if  xyz@gmail.com(1st user) is inactive for first user it should allow me to use the same email address for creating the second user with xyz@gmail.com.
Amit Chaudhary 8Amit Chaudhary 8
Please update code like below
trigger ContactDuplicatePreventer on Contact (before insert, before update) {
    Map<String, Contact> ConMap = new Map<String, Contact>();
	Set<Id> setContId = new Set<Id>();
	for (Contact Contact : System.Trigger.new) 
	{
		if ((Contact.Email != null) && (System.Trigger.isInsert || (Contact.Email != System.Trigger.oldMap.get(Contact.Id).Email)) ) 
		{
			setContId.add(Contact.id);
			if (ConMap.containsKey(Contact.Email)) {
				Contact.Email.addError('Another Contact has the same email address.');
			} else {
				ConMap.put(Contact.Email, Contact);
			}
		}
	}
   
    for (Contact Contact : [SELECT Email FROM Contact WHERE Email IN : ConMap.KeySet() and Id Not in :setContId ]) 
	{
        Contact.Email.addError('A Contact with this E-mail address already exists.');
    }
}

Let us know if this will help you
 
Priya 777Priya 777
HI Amit i gettiong below error


Apex trigger ContactDuplicatePreventer caused an unexpected exception, contact your administrator: ContactDuplicatePreventer: execution of BeforeInsert caused by: System.FinalException: SObject row does not allow errors: Trigger.ContactDuplicatePreventer: line 37, column 1