To Be, or Not To Be: the Empty Entity Reference

To be, or not to be, that is the question. Shakespeare never quite gets around to answering it, though. In Drupal 7, a similar existential question arises regarding entity references: Is it, or is it empty? Unlike Will, we can answer this question.

With other field types, we can check to see if the field is empty by doing something like this:

if (sizeof($form_state['values']['field_x'][LANGUAGE_NONE]) > 0)

but with an entityreference field, it is never completely empty. When it contains no value, $form_state['values']['field_x'][LANGUAGE_NONE] looks like this:

0 => array(
'target_id' => '',
'add_entityconnect_field_x_0_' => 'New content'
'edit_entityconnect_field_x_0_' => 'Edit content'

If you need to check whether target_id contains a valid value ( > 0 ) then you will need to interrogate it directly, but if the needs is only to check whether it is empty or non-numeric, use this:


Add new comment


  • Allowed HTML tags: <a href hreflang> <em> <strong> <cite> <blockquote cite> <code> <ul type> <ol start type> <li> <dl> <dt> <dd>
  • Missing filter. All text is removed
CAPTCHA This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.