Checking if a field is empty fails, on a node template file Trying to use empty() on a "longtext" field in a custom node template, the field is always reported not to be empty (whatever the field is empty or not). 

&lt;?php if (!empty($content['field_myfield'])): ?&gt;
  &lt;p&gt;additional content&lt;/p&gt;
  &lt;?php print render($content['field_landing_petition']);?&gt;
&lt;?php endif; ?&gt;


Why doesn't it work?  How else could I test for empty fields in the template file for a node?
$content['field_myfield'] is an array containing some keys; if you pass that array to empty(), you would not get back TRUE as result.
For example, I added a three fields to a content type (their types are "taxonomy term reference," "decimal," and "list of float values"); what you see in content['field_name'] is the following:







$content['field_name']['#items'] contains the content of the field; it's an array, as in Drupal 7 fields can contain multiple values.

The generic code that allows to check if the field is empty, which works for any field, without to know details about how the field values are stored, is similar to the following one:

// $field_name contains the name of the field.

$field = file_info_field($field_name);
$function = $field['module'] . '_field_is_empty';

foreach ((array) $content[$field_name]['#items'] as $item) {
  if (!$function($item, $field)) {
    $result = TRUE;
  } 
}

$is_empty = empty($result);


$is_empty is equal to TRUE when all the items of the field are empty, giving to empty the meaning given to the word from the module implementing the field. For example, the module could consider the field empty when its value is "none" or any similar value (e.g. "empty" or "&lt;none&gt;").