Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save lhuria94/222358f2c2e03fcc51ea0b286a15ee91 to your computer and use it in GitHub Desktop.
Save lhuria94/222358f2c2e03fcc51ea0b286a15ee91 to your computer and use it in GitHub Desktop.
entity-metadata-wrapper isset check.
<?php
$field_collection_item = field_collection_item_load($id);
$item_wrapper = entity_metadata_wrapper('field_collection_item', $field_collection_item);
// this results in an error if the field_contrib_headshot field is empty
$headshot = $item_wrapper->field_contributor->field_contrib_headshot->value();
Solution:
// EntityStructureWrapper implements the __isset() function according the principe of Overloading.
$headshot = array();
if (isset($item_wrapper->field_contributor->field_contrib_headshot)) {
$headshot = $item_wrapper->field_contributor->field_contrib_headshot->value();
}
// You can even directly call __isset method on wrapper.
print ($wrapper->__isset('field_property_sample') ? $wrapper->field_property_sample->value() : '';
// On nested field collections:
// When iterating over a list of field collections, and checking for a non-empty field collection
// nested within the first, isset() does not work. However, I found that checking:
foreach ($node_wrapper->field_fc_one AS $field_collection) {
// Grab a nested field collection, properly wrapped.
$nested_fc_wrapper = $field_collection->field_nested_fc;
// isset() or $wrapper->__isset('') do not work here, but this does:
if(nested_fc_wrapper->getIdentifier()) {
// Do some stuff
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment