+ Start a Discussion
r nareshr naresh 

how delete the contact record based on name what we enter name if exist otherwise will nedd to insert

Hi to all,
 i am new salsforce developer .i have written some code for delete the duplicate records based on what we enter the name if exist ,otherwise need to insert.

but im not getting the result please correct me! Thanks in advance

trigger duplicatecontactdelete on Contact (before delete) 
{
  list<id> ls=new list<id>();
    for(contact c:trigger.old)
    {
        ls.add(c.id);
    }
   list<contact> deletecontact =[select id,name from contact where name in:ls];
    if(deletecontact.size()>0)
    {
        delete deletecontact;
    }
}
 
Tarun_KhandelwalTarun_Khandelwal
Hi Naresh,

Your trigger is on Before delete event. And you want not to insert duplicate records. It's little bit confusing. Can you please explain your requirement with exapmle?
Vishal Negandhi 16Vishal Negandhi 16
You would usually not delete records if there's a duplicate. You can rather avoid the inserts to prevent duplication. 

Below is the updated code:

trigger duplicatecontactdelete on Contact (before insert
{
  Set<String> ls=new Set<String>();
    for(contact c:trigger.new)
    {
        ls.add(c.LastName); // comparing the last name on Contact
    }
   list<contact> duplicateContact =[select id,name from contact where lastname in:ls];

    if(deletecontact.size()>0)
    {
        for(Contact cont : trigger.new){
            for(Contact existingCont : duplicateContact){
                 if(cont.lastname == existingCont.lastName){
                 // add error message here
                 }
             }
        }
    }
}