Clear cache of parent (referencing) nodes by entityreference

Public
</> CopyGet raw version
php
  1. /**
  2.  * Implements hook_node_update().
  3.  */
  4. function MY_MODULE_node_update($node) {
  5. clear_cache_of_referencing_nodes($node);
  6. }
  7.  
  8. /**
  9.  * Implements hook_node_delete().
  10.  */
  11. function MY_MODULE_node_delete($node) {
  12. clear_cache_of_referencing_nodes($node);
  13. }
  14.  
  15. /**
  16.  * Helper function for clearing cache of referencing nodes.
  17.  *
  18.  * @param $node
  19.  */
  20. function clear_cache_of_referencing_nodes($node) {
  21. foreach (field_info_instances('node') as $bundle_name => $fields) {
  22. if ($bundle_name != $node->type) {
  23. foreach ($fields as $field_name => $instance) {
  24. $field = field_info_field($field_name);
  25. if ($field['type'] == 'entityreference' && in_array($node->type, $field['settings']['handler_settings']['target_bundles'])) {
  26. // Build query.
  27. $query = new EntityFieldQuery;
  28. $query->entityCondition('entity_type', 'node', '=')
  29. ->fieldCondition($field_name, 'target_id', $node->nid, '=');
  30.  
  31. if ($result = $query->execute()) {
  32. // Return node id.
  33. foreach ($result['node'] as $referencing_node) {
  34. cache_clear_all("field:node:$referencing_node->nid", 'cache_field');
  35. }
  36. }
  37. }
  38. }
  39. }
  40.  
  41. }
  42. }