Professional in Drupal web development, theme designing, consultation and training

[Snippet] The right way rendering field in Drupal 7

29 Apr 2014 - 07:27 am

The best part in Drupal 7, it was totally a massive upgrade from Drupal 6 by introducing of entity concept. This is really awseome since we do not depend on "nodes" concept anymore. Supporting the entity, more and less in D7 we could expand used of Field API which provide custom field design through GUI.

Its not stop there. For themers, we able to print and render any field from any entity bundle directly into theme files without sacrifice write up SQL query code. By using node_load(), we load everything node data for nid targeting.

The best practices to render specific field is using field_get_items(). After that pass this array into field_view_value() to get the raw value and sanitize them before rendering.

$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);

This method make the render value aware towards language tag. Direct calling raw value like this:

$value = $node->field_name['und'][0]['safe_value'];

is not a best practice!

render field
entity API
field API