2 min read

Fields rendering in Drupal 7

Many developers use node fields directly in templates and hooks, accessing them through node attributes.

// Incorrect.
$tag_tid = $node->field_tags[LANGUAGE_NONE][0]['tid'];
$description = $node->body[LANGUAGE_NONE][0]['safe_value'];

There are several reasons why you should avoid this:

  • Using LANGUAGE_NONE or the value 'und' limits multilingual support.
  • 0 selects only one value.
  • tid, safe_value, etc. - different fields have different types of values.

To display fields correctly, use the field_view_field() function:

$field_tags = field_view_field('node', $node, 'field_tags');
$output = render($field_tags);

This returns a render array that uses templates and other field formatting functions.

If you need to specify the display type (default is 'default'):

$field_tags = field_view_field('node', $node, 'field_tags', array('type' => 'teaser'));
$output = render($field_tags);

Other options:

$options = array(
  'label' => 'inline', // 'inline', 'above', 'hidden'; default 'above'
  'type' => 'full',
);
$body = field_view_field('node', $node, 'body', $options);
$output = render($body);

There are also functions for displaying only one field value: field_get_items() and field_view_value().

Examples

Long trimmed text:

/** types:
 * text_default
 * text_plain
 * text_trimmed
 * text_summary_or_trimmed
 */
$options = array(
  'type' => 'text_trimmed',  
  'settings' => array(
   'trim_length' => 50,
  ),
);
$body = field_view_field('node', $node, 'body', $options);
$output = render($body);

Link to taxonomy term:

/** types:
 * taxonomy_term_reference_link
 * taxonomy_term_reference_plain
 * taxonomy_term_reference_rss_category
 */
$options = array(
  'type' => 'taxonomy_term_reference_link',
);
$field_tags = field_view_field('node', $node, 'field_tags', $options);
$output = render($field_tags);

Displaying a single image:

$options = array(
  'type' => 'image',
  'settings' => array(
    'image_style' => 'thumbnail',
    'image_link' => 'content', // content, file
  )
);
$images = field_get_items('node', $node, 'field_image');
$field_image = field_view_value('node', $node, 'field_image', $images[0], $options);
$output = render($field_image);

Additional documentation: