+ Start a Discussion
Sindhu AmbarkarSindhu Ambarkar 

When new record is created in account object before new record is inserted into account,delete all the contact records with this account name it is working as expected

Hi,

trigger contactrecords on Account (before insert)
 {

    List<String> myname=new List<String>();
    for(Account a:trigger.new)
    {
    myname.add(a.name);
    }
    List<contact> mycontact=[select id,name from contact where name in:myname];
    delete mycontact;
}

Please help me.
Jithin Krishnan 2Jithin Krishnan 2
trigger contactrecords on Account (before insert)
 {
     List<Contact> mycontact=new List<Contact>();
     for(Account a: Trigger.New)
     {
          for(Account old: [select id from Account where name=:a.name]){
    	      mycontact.addAll(old.Contacts);
         }
     }
      delete mycontact;
}
Please try the above code and let me know.
Thanks!
Praful IngolePraful Ingole
Actually i got the error  after running this code .the error is like that Invalid bind expression type of Schema.SObjectField for column of type String,
can you tell me a correct answer of this
Hitesh NimjeHitesh Nimje
not working the above code 
Hitesh NimjeHitesh Nimje
Hi  sindhu,
below is the working code for the above trigger,
hope you problem will resolved now.....
trigger:-
  • trigger contactrecords on Account (before insert,before update,)
  •  {
  •          List<String> myname=new List<String>();
  •     for(Account a:trigger.new)
  •     {
  •     myname.add(a.name);
  •     }
  •     List<contact> mycontact=[select id,name from contact where name in:myname];
  •     delete mycontact;
  • }
NiwedNiwed
Hello Sindhu,

I went through your code, the trigger work if your requirement is something like deleting the existing record of Contact where the contact name is as same as the newly created account name then it will delete the record in the contact.

You may also add event 'after update' on the trigger if any account name is updated with a similar name in the contact record.
 
trigger AccountContatTrigger on Account (before insert,after update) {
List <String> myName = new List<String> ();
    for(Account acc:Trigger.New){
        myName.add(acc.name);
    }
List <Contact> myContact= [Select id,name from Contact where name IN:myName];
delete myContact;
}

 
Sprutiraj Panda 7Sprutiraj Panda 7
Both Code was not working properly 
suppose same account was there one account was contact but when we create a account on same name the prebious conatct name was not delete it was ther on the same account