Drupal - How do I render a field value including its format?
While you could spend a lot of time dissecting how the Field API works, you really should be using the Field API directly to render field content instead of querying the database yourself. There's a lot of encapsulation and abstraction added to fields that will awaken the Old Gods if bypassed.
Using the Field API, if you want the whole formatted field, complete with label and all values, you want to use field_view_field()
:
$nid = 1;
$node = node_load($nid);
$output = field_view_field('node', $node, 'field_foo');
// $output is a render array, so it needs to be rendered first
print render($output);
If you just want to display the formatted value of one item in a field, you need to use field_view_value()
, which is a little more involved:
// Must load field content for entity before using field_view_value()
$fields = field_get_items('node', $node, 'field_foo');
// $index corresponds to the value you want to render. First value = 0.
$index = 0;
$output = field_view_value('node', $node, 'field_foo', $fields[$index]);
print render($output);
If you want to use a formatter other than the default specified for the field instance, pass it using the $display
parameter in either field_view_field()
or field_view_value()
:
$display = array('type' => 'my_formatter');
$output = field_view_field('node', $node, 'field_foo', $display);