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
Kenn K.Kenn K. 

Prevent Parent Account to be deleted if it has a child account

I am trying to figure out the best way to prevent users from deleting and Account if it has a child account.

So the scenario will be the users will have to delete all the child accounts first before they can delete the parent.

Any guidance will be highly appreciated.




Sample code which should help you just replace the objectname with Account


trigger onParentObjectDelete on CustomObject__c (before delete){
    List<Id> idsToQuery = new List<Id>{};
    for(CustomObject__c a:{

    //query all child records where parent ids were deleted
    ChildObject__c[] objsToDelete = [select id from ChildObject__c where ParentId__c IN :idsToQuery];

    delete objsToDelete; //perform delete statement