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
AnjaneyluAnjaneylu 

Trigger

HI Experts,
Requirement: Delete the  contacts with same account name which i am going to create with before insert event..
I have written this code, but it is not working.. please suggest me ..


trigger Delete_Duplicate_Contact_With_same_accountName on Account (Before insert) {
list<contact> con = [select id, lastname from contact];
for(account a : trigger.new){
if(a.name== con.lastname){
delete con;
}
else{
create a
}
}



Thanks and regards,
Anji
 
Best Answer chosen by Anjaneylu
SantoshChitalkarSantoshChitalkar
Hi Anji,

Use following code - 
 
trigger Delete_Duplicate_Contact_With_same_accountName on Account (Before insert) {
         list<contact> lstContact = [select id, firstName, lastname from contact];
         list<contact> delContact = new list<contact>();
         for(account a : trigger.new){
              for(Contact c :  lstContact){
                    if(a.firstName == c.firstName && a.LastName == c.lastname){
                         delContact.add(c);
                    }
              }
          }
          if(delContact.size() > 0)
                 delete delContact;
}

Let us know if this answers your question.

Regards,
Santosh Chitalkar

All Answers

Surendra nuneSurendra nune
You have to check both last name and firstname.

 
SantoshChitalkarSantoshChitalkar
Hi Anji,

Use following code - 
 
trigger Delete_Duplicate_Contact_With_same_accountName on Account (Before insert) {
         list<contact> lstContact = [select id, firstName, lastname from contact];
         list<contact> delContact = new list<contact>();
         for(account a : trigger.new){
              for(Contact c :  lstContact){
                    if(a.firstName == c.firstName && a.LastName == c.lastname){
                         delContact.add(c);
                    }
              }
          }
          if(delContact.size() > 0)
                 delete delContact;
}

Let us know if this answers your question.

Regards,
Santosh Chitalkar
This was selected as the best answer
AnjaneyluAnjaneylu
Hi  
Santosh Chitalkar, Surendra nune

my requirement is when i create the new contact then contact phone number has to be update with account phone number for all the contacts with after insert event.
i have written this code,  i am getting error. please suggest me 


trigger update_contactPhone_With_AccountPhone on Contact (after insert) {
list<contact> updatecon = new list<contact>();
list<account> accs = [select id, name,phone from account];
for(contact con :trigger.new){
for(account acc :accs){
if(con.accountid==acc.id){
con.phone = acc.phone;
updatecon.add(con);
}
}

}if(updatecon.size()>0)
update updatecon;
}