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:

entityreference_field_is_empty()

Of course, the Drupal Community isn't the only place to give back. It's a complex world, and there are as many worthy causes as their are melodies, with most being served by multiple charitable organizations. Here are a few of those that strike a 7th chord with me.