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
Hermann OuréHermann Ouré 

Trigger Contact Duplicates

Hello,
I am trying to write a trigger to stop user creating contact with the same email address. But I keep getting an error
 System.NullPointerException: Attempt to de-reference a null object
on line 8 for:

conMap.get(c.Id).Email
How can I fix this error
Thanks
 
trigger ContactDuplicate on Contact (before insert) {
    
    Map<Id, Contact> conMap = new Map<Id, Contact>([SELECT Id, Email FROM Contact WHERE Email != null]);
    System.debug('Map ' +conMap);
      
    if(Trigger.isBefore && Trigger.isInsert) {
        for(Contact c : Trigger.New) {
            if(c.Email != null && c.Email == conMap.get(c.Id).Email) {
                c.Email.addError('Duplicate Contact');
            }
        }
    }
}

 
Best Answer chosen by Hermann Ouré
CharuDuttCharuDutt
Hii Hermann
Try Below Code
trigger PreventDuplicateContacts on Contact (before insert) {
    Set <String> emailSet = new Set<String>(); 
    for (contact con:trigger.new) {
        emailSet.add(con.Email);
        
    }
    List <Contact> contactList = [SELECT Email,Phone FROM Contact WHERE email IN :emailSet];

    for (contact con:trigger.new) {
        If (contactList.size() > 0) {
            
          con.Email.adderror( 'Duplicate Contact Found. Use Existing Contact.' );
            
        }
    }
}
Pleae Mark It As Best Answer If It Helps
Thank You!