0

i am new to the apex development, i am trying to learn apex triggers, how to automatically delete child records when parent record is deleted, i know through M-D relationship this can be achieved, but i need design a trigger for learning, here i have designed the trigger on Account and Related Contact_c custom object, i am getting the error, i have refered a below link but still i could not achieve the functionality

https://developer.salesforce.com/forums/?id=906F000000092e8IAA

trigger deleteChildrenOnParentDelete on Parent_Object__c (before delete) 
{   
        List<Parent_Object__c> parentList = new List<Parent_Object__c>([SELECT Id FROM Parent_Object__c]);                 
        Map<Id,Parent_Object__c> childMap = new Map<Id,Parent_Object__c>();
            For(Parent_Object__c c: parentList)
            {
                childMap.put(c.ID,c);
            } 

        List<Child_Object__c> childList = new List<Child_Object__c>();
            For(Child_Object__c c: [select Id,Parent_Object__c from Child_Object__c where Parent_Object__c IN: childMap.Keyset()])
            {
                childList.add(c);
            } 
                Delete childList;                             
}
| improve this question | | | | |
1

To delete child records when parent is deleted in case of lookup relationship.

trigger deleteChildrenOnParentDelete on Parent_Object__c (before delete) 
{   
   if(trigger.isDelete && Trigger.isBefore){

            List<Child_Object__c> childList = new List<Child_Object__c>();
            For(Child_Object__c c: [select Id,Parent_Object__c from Child_Object__c 
                     where Parent_Object__c IN: trigger.oldMap.KeySet()])
            {
                childList.add(c);
            } 
            Delete childList;    
       }                         
}
| improve this answer | | | | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.