Drupal - Checking for existence for a field on an an entity_metadata_wrapper

Simply call the PHP function isset():

$headshot = array();
if (isset($item_wrapper->field_contributor->field_contrib_headshot)) {
  $headshot = $item_wrapper->field_contributor->field_contrib_headshot->value();
}

EntityStructureWrapper implements the __isset() function according the principe of Overloading.


Any time there is an entity reference or field collection, isset() has never worked for me. What does seem to work any time we have an entity reference is doing:

if($wrapped_entity->entity_reference_field->getIdentifier()) {
  // This code only fires if there is an entity reference or field collection set.
}

It looks like you have an entity_reference somewhere in there due to the method chaining. But, look at the __isset() method for EntityStructureWrapper.

Check like:

$has_headshot = $item_wrapper->field_contributor->__isset('field_contrib_headshot');

and then use an IF block to do your logic ...

EDIT:

$has_headshot is now valid check desired.

Tags:

Entities