2

I have two content types: Type A and Type B. I have a Node Reference field on content Type A (using References module) that is set to be displayed using the "Rendered Node" version of that referenced node. It references nodes of content Type B. How can I print the content of that field as a rendered node in a custom template file for content Type A?

  • what do you mean by "print the content of that field"? do you mean body field? – Aboodred1 Jun 10 '13 at 19:21
  • Can you confirm that you are using drupal.org/project/References ? I just want to edit the question, as how the field is stored varies between the various reference modules for Drupal 7. – mpdonadio Jun 10 '13 at 22:55
  • @MPD - Good catch. I have edited my answer. – Triskelion Jun 10 '13 at 23:50
  • @MPD, yes, I am using References. – hockey2112 Jun 11 '13 at 14:00
4

In your $node object, you will find the subordinate node object at $node->field_fieldname['und'][0]['node']. To render this in a page you have to turn it into a renderable array. You do this with node_view(),specifying the type of display mode. Try:

<?php
if(isset($node->field_fieldname['und'][0]['node'])) {
  $second_node = $node->field_fieldname['und'][0]['node'];
  $view_mode = 'teaser'; // or 'full' as the case may be
  $render_array = node_view( $second_node, $view_mode);
  print render($render_array);
}
?>

EDIT

MPD is correct. The above assumes that the field is a Node Reference field. If you are using an Entity Reference field, the code should be changed to:

 <?php
    if(isset($node->field_fieldname['und'][0]['entity'])) {
      $second_node = $node->field_fieldname['und'][0]['entity'];
      ...
  • Shouldn't that be target_id and not entity? – mpdonadio Jun 11 '13 at 12:59
  • @MPD - Node reference uses ['nid'] for the id and ['node'] for the object. Entity reference uses ['target_id'] for the id and ['entity'] for the object. The node (or entity) object is included in the field data. Why access the id and separately load the object when it is already there? – Triskelion Jun 11 '13 at 15:56
  • @Triskelion Odd. I have never seen anything other than ['target_id'] when I dpm() or print_r() a node. – mpdonadio Jun 11 '13 at 18:54
  • @MPD - I have found that the global $node may be incomplete. When I do a print_r(), I usually precede it with $full_node=node_load($node->nid). You would be amazed at the differences I find :-) – Triskelion Jun 11 '13 at 19:16

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.