Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Drupal 7 show empty fields

Parent Feed: 

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' => ' '),
      );
    }
  }
}
?>

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

Author: 
Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web