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
yuvaraj repalleyuvaraj repalle 

hi all how to write a trigger to delete all contact records on account when the account is deleted

Raj VakatiRaj Vakati
Use this code
 
trigger deleteAccountRecord on Contact (after delete) {

        List<ID> contactIDList = new List<ID>();

    if(Trigger.isDelete){
        for(Contact contactToDelete: Trigger.old) {
                    contactIDList.add(contactToDelete.AccountId);
        }
      
       
       List<Account> DelAccountRecordList = [select id from Account where Id IN:contactIDList];

        if(DelAccountRecordList.size() >0){
           delete DelAccountRecordList ;
         
        }
     }
  }

 
Manvendra Chaturvedi 26Manvendra Chaturvedi 26
Hi,

When we delete any Account , its contact automatically get deleted . 
No need to write trigger to delete contact
Raj VakatiRaj Vakati
Thats true ... When you delete account associated contact are deleted .. 
Deepali KulshresthaDeepali Kulshrestha
Hi yuvaraj,

Please try this code if you want to delete all the contacts associated with an account on deletion of account record:

trigger TriggerTo_Delete_ChildRecords on Account (before delete) {
    
    //To store parent ids
    list<id> AccountIds=new list<id>();
    for(Account accountVar:trigger.old)
    {
        AccountIds.add(accountVar.id);
    }  
    //Collecting all child records related to Parent records
    list<contact> listOfContacts=[select id from Contact where accountid in :AccountIds];
    system.debug('listOfContacts'+listOfContacts);
    //deleting child records
    delete listOfContacts;
}

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks and Regards,
Deepali Kulshrestha