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.