Rendering fields in Drupal 7

The short answer:

use field_view_field();

The long answer:

In drupal 6 it was perfectly common to poke around in the node object to get your values and print them.
With the field api and entities in drupal 7 however we need to change that habit and use the functions drupal provides us.
Luckily field_view_field() comes in here. 

$output = field_view_field('node', $node, 'field_name');

Combine it with

Combine it with field_get_items and node_load functions to get your values.
Here is an example:

$node = node_load($nid);
$field = field_get_items('node', $node, 'field_name');
$output = field_view_value('node', $node, 'field_name', $field[$delta]);
// $delta being the offset of your field array, usually 0 on single fields

And just for fun, here's a final example of passing in some formatter options to specify an imagecache preset, and make the field link to the node. This would work the same for both field_view_value() and field_view_field().

$node = node_load($nid);
$image = field_get_items('node', $node, 'field_image');
$output = field_view_value('node', $node, 'field_image', $image[0], array(
  'type' => 'image',
  'settings' => array(
    'image_style' => 'thumbnail',
    'image_link' => 'content',
  ),
));

Add new comment