Rendering Drupal 7 field values using the FieldAPI

Ever rendered a field value from a node object like this before
  $value = $node->field_name['und'][0]['safe_value']; 
That was common in drupal 6. I do the same even in drupal 7 but found the best way of rendering a field value from an entity using the Field API that ships with drupal 7. The Field API allows custom data fields to be attached to Drupal entities and takes care of storing, loading, editing, and rendering field data. Any entity type (node, user, etc.) can use the Field API to make itself "fieldable" and thus allow fields to be attached to it. Sometimes you may need to output a field value of an entity(node,user, etc). An example would be to output the field value of an entity say the price of a product node. You may have written your code to look like this
$price = $node->field_price['und'][0]['safe_value'];
I would like to explain three API functions of the Field API to explain the right way of rendering field values. Firstly, is the field_get_items() which returns the field items in the language they currently would be displayed and its returning value is an array of field items keyed by delta if available. Also is the field_view_value() which returns a renderable array for a single field value.
$node = node_load($nid);
$field = field_get_items('node', $node, 'field_name');
$output = field_view_value('node', $node, 'field_name', $field[0]);
print render($output);
You need to note that field_get_items() returns raw values so passing the raw values through field_view_value() handles the sanitizing of the values. The third API function is field_view_field() which returns a renderable array for the value of a single field in an entity. The resulting output is a fully themed field with label and multiple values. This function can be used by third-party modules that need to output an isolated field. Example
print render(field_view_field('node', $node, 'body')); 
This will output a renderable array for the field value. The Field API really makes this simple to work with field values and using these API functions means that proper sanitisation and the security risk are taking care of for you.
Share