Drupal - Check if a field is empty

If you read up on the documentation the function returns FALSE if there is no data. isset() would actually fail because you are assigning FALSE to the variable so it's actually been set to something. The correct syntax would be:

$field = field_get_items('node', $node, 'field_post_image');
if ($field) {
   //Do something with the field
}
else{
   //There are no results
}

You could use the following snippet to verify if a field is empty.

$info = field_info_field($field_name);
$function = $info['module'] . '_field_is_empty';

if (function_exists($function)) {
  $value = field_get_items('node', $node, $field_name);
  $is_empty = $function($value[0], $info);
}

This code is safer, as different fields are considered empty under different conditions. See, for example, the difference between file_field_is_empty(), number_field_is_empty(), and taxonomy_field_is_empty(): taxonomy_field_is_empty() checks the tid property of the $item parameter, while number_field_is_empty() checks the value property of the same parameter. Custom fields could require a more complex condition to be verified, in order to consider the field empty.

The description for hook_field_is_empty() given in the documentation is the following one:

Define what constitutes an empty item for a field type.


We found the raw value in ($content['field_name']['#items'][0][value]), so you can determine if the field is empty or not with the expression

(!empty($content['field_name']['#items'][0][value]))

where field_name matches the name of the desired field.

Tags:

Entities

7