In a theme's node.tpl.php, we can easily render a field view using Drupal's render().

For example, we have a field name field_integer with the label My integer. To display the field in the node.tpl.php, we can just call it out using render($content['field_integer']);, which will display like the following (Assuming it is the default manage display setting for the field):

My integer:
3 200

However, what if you want to render the field in your custom module? You won't be able to use render($content['field_name']).

There are many ways to go about this. One of the common and easiest way would be to first do a node load, and print out the value directly from the array. In our case, this is how it is done:

$node = node_load(5); // Your node nid
print $node->field_integer[LANGUAGE_NONE][0]['value'];

This way, it will print out the raw value, that is 3200.

What if we want to print with the label and formatting, just like how we want it in node.tpl.php? This is how we do it:

$field = field_view_field('node', $node, 'field_integer');
print drupal_render($field);

Instead of using render() like before, we use drupal_render() instead.

How about printing a custom label and at the same time having a field being formatted? This is how we do it:

// We need to get a list of items first

$field_items = field_get_items('node', $node, 'field_integer');



// Get the instance for display settings.

$instance = field_read_instance('node', 'field_integer', 'content_type'); // Change the content type machine name



// And then only print with the delta

$field = field_view_value('node', $node, 'field_integer', $field_items[0], $instance['display']['default']);

print t('My awesome integer is ') . drupal_render($field);

The above code will output the following:

My awesome integer is 3 200

It will print out just it's formatted value, without any additional HTML ids or classes wrapper around the field. Just that it has to perform additional function call to get the display settings with field_read_instance

By using field_view_field or field_view_value as compared to $node->field_name[LANGUAGE_NONE][0]['value'], we can take the advantage of Drupal's Field API manage display settings. For example, we can change the display from space separated to a comma separated integer value easily using the proper Drupal way.

Published on 3 September 2012 - 6:20am