Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Select an option

  • Save msankhala/3bf4d872826c4707ce1a6fbee007d11d to your computer and use it in GitHub Desktop.

Select an option

Save msankhala/3bf4d872826c4707ce1a6fbee007d11d to your computer and use it in GitHub Desktop.
load all referenced node from node reference field.
<?php
// Get all referenced node from a node reference field.
function get_related_nodes($master_nid, $field_name) {
// Load the 'master' node
$master_node = node_load($master_nid);
// Get the node reference items attached to this node
$items = field_get_items('node', $node, $field_name);
// Loop through and grab the nids
$nids = array();
foreach ($items as $item) {
$nids[] = $item['nid'];
}
// Return the fully loaded reference nodes
return node_load_multiple($nids);
}
// https://www.drupal.org/node/2321535
// Using entity metadata wrapper.
function custom_entity_load($id) {
$my_entity = reset(entity_load('my_custom_entiy_with_er_field', array($id)));
$wrapper = entity_metadata_wrapper('my_custom_entiy_with_er_field', $my_entity);
$my_entity->children = $wrapper->my_entity_reference_field->value();
return $my_entity;
}
// The original ER field data is still there at
// $my_entity->field_my_entity_reference_field but there's now also an array of
// the entities specified in the field with their complete properties at /
// $my_entity->children. The child entity isn't fieldable so that works for me.
// Not sure if it would include all the fields as well for entities
// that do have them.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment