How to display field labels even if field is empty ?

Public
</> CopyGet raw version
php
  1. /**
  2.  * Implements hook_field_attach_view_alter().
  3.  *
  4.  * Show titles of empty fields.
  5.  */
  6. function example_field_attach_view_alter(&$output, $context) {
  7. // We proceed only on nodes.
  8. if ($context['entity_type'] != 'node' || $context['view_mode'] != 'full') {
  9. return;
  10. }
  11.  
  12. $node = $context['entity'];
  13. // Load all instances of the fields for the node.
  14. $instances = _field_invoke_get_instances('node', $node->type, array('default' => TRUE, 'deleted' => FALSE));
  15.  
  16. foreach ($instances as $field_name => $instance) {
  17. // Set content for fields they are empty.
  18. if (empty($node->{$field_name})) {
  19. $display = field_get_display($instance, 'full', $node);
  20. // Do not add field that is hidden in current display.
  21. if ($display['type'] == 'hidden') {
  22. continue;
  23. }
  24. // Load field settings.
  25. $field = field_info_field($field_name);
  26. // Set output for field.
  27. $output[$field_name] = array(
  28. '#theme' => 'field',
  29. '#title' => $instance['label'],
  30. '#label_display' => 'above',
  31. '#field_type' => $field['type'],
  32. '#field_name' => $field_name,
  33. '#bundle' => $node->type,
  34. '#object' => $node,
  35. '#items' => array(),
  36. '#entity_type' => 'node',
  37. '#weight' => $display['weight'],
  38. 0 => array('#markup' => '&nbsp;'),
  39. );
  40. }
  41. }
  42. }