Drupal 7 show empty fields

In this note I would like to share solution for quite common task: show node fields titles even if field are empty. By default if the field is empty it is not included in the node. But practically sometimes client would like to see title of the field even if the field value is not set. As this task has made me debugging for a while I hope it will save someone else's time.

So solution is to use hook_field_attach_view_alter(). This hook is invoked after field module added fields renderable arrays to the content of the node.

<?php
/**
 * Implements hook_field_attach_view_alter().
 *
 * Show titles of empty fields.
 */
function example_field_attach_view_alter(&$output, $context) {
  // We proceed only on nodes.
  if ($context['entity_type'] != 'node' || $context['view_mode'] != 'full') {
    return;
  }
 
  $node = $context['entity'];
  // Load all instances of the fields for the node.
  $instances = _field_invoke_get_instances('node', $node->type, array('default' => TRUE, 'deleted' => FALSE));
 
  foreach ($instances as $field_name => $instance) {
    // Set content for fields they are empty.
    if (empty($node->{$field_name})) {
      $display = field_get_display($instance, 'full', $node);
      // Do not add field that is hidden in current display.
      if ($display['type'] == 'hidden') {
        continue;
      }
      // Load field settings.
      $field = field_info_field($field_name);
      // Set output for field.
      $output[$field_name] = array(
        '#theme' => 'field',
        '#title' => $instance['label'],
        '#label_display' => 'above',
        '#field_type' => $field['type'],
        '#field_name' => $field_name,
        '#bundle' => $node->type,
        '#object' => $node,
        '#items' => array(),
        '#entity_type' => 'node',
        '#weight' => $display['weight'],
        0 => array('#markup' => '&nbsp;'),
      );
    }
  }
}
?>

Hope you find it useful and please let me know if you know any other nicer way to accomplish this task.

Comments

Thank you for your sharing, really I was looking for how to do that.

Thanks for the info. Please could you explain how to implement the hook for those of us who don't know what to do with the above code...could it be made into a simple module to get more exposure for all Drupal users? Thanks

In this particular case you need to create module "example" that will consists of two files example.info and example.module. In example.module file you just paste code above. Hope it helps. For more information about how to write your own module please refer to http://drupal.org/node/361112

Hi, and thank you! This info saved me a lot of time. I was just wondering if there is a way to set a value for the field instead of leaving it empty.