Skip to content

Instantly share code, notes, and snippets.

@scottrigby
Last active September 22, 2016 16:38
Show Gist options
  • Save scottrigby/afe3bbfeb8dcf91d55c3590b3d5c377a to your computer and use it in GitHub Desktop.
Save scottrigby/afe3bbfeb8dcf91d55c3590b3d5c377a to your computer and use it in GitHub Desktop.
EntityMetadateWrapper isset

For future ref, the source for this technique can be found on drupal.org:

Atomox commented 2 years ago Trying to load a field on an entity, but an unset field throws an exception, and breaks your page?

There doesn't seem to be a consistent way to check if the field is set. However, try these approaches:

For simple fields, entityMetadataWrappers have extended the isset() to work with simple fields.

Either use isset() as normal, or:

if($wrapped_entity->__isset('field_name_we_are_checking') {

// This code only fires if there is basic field, and it was set. }

> For entity references (and Field Collections), this method does not work. Instead, check if the field has an identifier:
> 
> ```
if($wrapped_entity->entity_reference_field->getIdentifier()) {
>   // This code only fires if there is an entity reference or field collection set.
> }

These examples are reiterated on drupal.stackexchange.com.

I prefer these code examples over straight isset() wrapping a piece of the wrapper object, because of how these two methods are defined. See documentation for EntityStructureWrapper::__isset, and EntityDrupalWrapper::getIdentifier.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment