+ Start a Discussion
sfdc freshersfdc fresher 

duplicate email check in contact

i AM getting below error
Error: Invalid Data. 
Review all error messages below to correct your data.
Apex trigger Int4_DuplicateEmailCheck caused an unexpected exception, contact your administrator: Int4_DuplicateEmailCheck: execution of BeforeInsert caused by: System.NullPointerException: Attempt to de-reference a null object: Trigger.Int4_DuplicateEmailCheck: line 16, column 1


Code is below.



trigger DuplicateEmailCheck on Contact (before insert,before update) {

    Set<Id> cid=new Set<ID>();
    for(Contact c:Trigger.new)
    {
        if(c.Email!=NUll)
        {
           cid.add(c.id); 
        } 
    }
    Map<ID,Contact> mcp=new Map<Id,Contact>([select id,Email from Contact where Id in :cid]);
   
   for(Contact c:Trigger.new)
   {
       if(c.Email!=null && ((mcp.get(c.Id)).Email)A==c.Email)
       {
           c.addError('Email Cant be duplicated');
        }
   }
}
Raj VakatiRaj Vakati
try this code
 
trigger DuplicateEmailCheck on Contact (before insert,before update) {

    Set<String> cid=new Set<String>();
    for(Contact c:Trigger.new)
    {
        if(c.Email!=NUll)
        {
           cid.add(c.Email); 
        } 
    }
    //Map<S,Contact> mcp=new Map<Id,Contact>([select id,Email from Contact where EMAIL in :cid]);
   
   List<Contact> emailsforExisting = [select id,Email from Contact where EMAIL in :cid] ; 
    Set<String> emailsExist=new Set<String>();
   for(Contact c : emailsforExisting){
	   emailsExist.add(c.Email);
   }
   
   for(Contact c:Trigger.new)
   {
       if(emailsExist.contains(c.Email))
       {
           c.addError('Email Cant be duplicated');
        }
   }
}

 
Raj VakatiRaj Vakati
Record id is not avaiable in before insert soo you got  error 
Ajay K DubediAjay K Dubedi
Hi,

Below code can fulfill your requirements. Hope this will work for you.

trigger contactDuplicatePreventer on Contact (before insert, before update){
                               
    Map<String, Contact> contactMap = 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 (contactMap.containsKey(Contact.Email)) {
                Contact.Email.addError('Another new Contact has the' + 'same email address.');                      
            } 
            else 
            {
                contactMap.put(Contact.Email, Contact);
            }
       }
    } 
    for (Contact contact : [SELECT Email FROM Contact WHERE Email IN :contactMap.KeySet()])
    {
        Contact newContact = contactMap.get(Contact.Email);
        newContact.Email.addError('A Contact with this email' + 'address already exists.');                      
    }
}

Please mark this as best answer if this solves your problem.

Thank you
Ajay Dubedi