OK in drupal 6 I had a rule set up to delete child nodes when the parent node was deleted. I used VBO module with a view and the action Execute a VBO programmatically on node.

There is no longer an action to do this in drupal 7. Can anyone advise how to go about doing this with the rules available.

Cheers

Comments

bradallenfisher’s picture

This handy little function will delete all children nodes that reference a parent node when you delete it. Helpful if you have multiple users adding content to your site.  Or if a workflow of attaching many nodes to one node has a short life cycle. For instance, if a system of petitions attaches requests to it, it is helpful to be able to delete all requests when you delete the petition.

Create a simple module with the code below

In the info file:

name = mymodule
description = Utility module that performs operations on nodes
project = Custom Modules
core = 7.x

In the module file:

/**
 * Implements hook_node_delete().
 */
function mymodule_node_delete($node) {
	
  $query = new EntityFieldQuery();
  $query->entityCondition('entity_type', 'node')->fieldCondition('field_referencing_parent_node', 'target_id', $node->nid);
  $results = $query->execute();
	
  if (!empty($results['node'])) {
    $nodes = array_keys($results['node']);
    node_delete_multiple($nodes);
  }	
}

Replace field_referencing_parent_node with the field that references the parent node. Replace mymodule with the actual module name. Entity Field Query will do the rest.

Check out more recipes here: http://bytesofweb.com/recipe/delete-all-children-nodes-when-parent-deleted

ayesh’s picture

Does this work when multiple nodes refer the same node?
Suppose node A and B refer node Y, and will this module will delete node Y when deleting node B, making node A's reference invalid, right?