I have recently been trying to update my code to use entity wrappers to access field values. Now I have this:
$wrapper = entity_metadata_wrapper("node", $nid);
print($wrapper->field_property_sample()->value());
instead of this:
print($node->field_property_sample[LANGUAGE_NONE][0]["value"]);
The problem is sometimes I encounter this:
EntityMetadataWrapperException: unknown data property field_property_sample.
Is there a way for me to workaround this?
I have about 10 of these fields that can throw this exception and it is really getting ugly
$wrapper = entity_metadata_wrapper("node", $nid);
try {
print($wrapper->field_property_sample()->value());
} catch (EntityMetadataWrapperException &e){
print("");
}
/** repeat 10 times **/
Is there some function that I can more or less call like this?
$wrapper = entity_metadata_wrapper("node", $nid);
print($wrapper->field_property_sample->exists() ? $wrapper->field_property_sample->value() : "" );
/** repeat 10 times **/
Yep, you can just use existing features of the PHP language
try {
print($wrapper->field_property_sample->value());
}
catch (EntityMetadataWrapperException $e) {
// Recover
}
Or, since EntityMetadataWrapper
implements __isset()
you can use that:
print isset($wrapper->field_property_sample) ? $wrapper->field_property_sample->value() : '';
With reference to Clive's answer, you can use __isset()
like this:
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
}
}
Using field_property_sample()
doesn't make sense, because:
$wrapper->field_property_sample()
is used to call a class method
$wrapper->field_property_sample
is used to get a value of the class property
Property is the variable which you want to use, class method is the function which you want to call.
So using:
$wrapper->field_property_sample->value();
is the correct syntax.
For proper usage of Entity metadata wrappers, check: Entity metadata wrappers page.
Here is some code example:
try {
$wrapper = entity_metadata_wrapper('node', $node);
$wrapper->field_property_sample = 'some data';
$wrapper->field_multi_sample = array('1st', '2nd');
$wrapper->save();
}
catch (EntityMetadataWrapperException $e) {
watchdog_exception('my_module', $e);
}
To print, use:
print($wrapper->field_property_sample->value());
or dpm()
, dd()
from Devel module.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With