Monday, 17 October 2016

Trigger to Delete All child records when parent record is deleted.

Deleting all child records when parent record is deleted.

Code:

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;
}

No comments:

Post a Comment