EntityMetadataWrapperException:字段的未知数据属性

fer*_*ale 5 php drupal drupal-7

我最近一直在尝试更新我的代码以使用实体包装器来访问字段值.现在我有这个:

$wrapper = entity_metadata_wrapper("node", $nid);
print($wrapper->field_property_sample()->value());
Run Code Online (Sandbox Code Playgroud)

而不是这个:

print($node->field_property_sample[LANGUAGE_NONE][0]["value"]);
Run Code Online (Sandbox Code Playgroud)

问题是我有时遇到这个问题:

EntityMetadataWrapperException:未知数据属性field_property_sample.

我有办法解决这个问题吗?

我有大约10个这样的字段可以抛出这个异常,它真的变得很难看

$wrapper = entity_metadata_wrapper("node", $nid);

try {
  print($wrapper->field_property_sample()->value());
} catch (EntityMetadataWrapperException &e){
  print("");
}

/** repeat 10 times **/
Run Code Online (Sandbox Code Playgroud)

是否有一些我可以或多或少地这样称呼的功能?

$wrapper = entity_metadata_wrapper("node", $nid);
print($wrapper->field_property_sample->exists() ? $wrapper->field_property_sample->value()  : "" );

/** repeat 10 times **/
Run Code Online (Sandbox Code Playgroud)

Cli*_*ive 8

是的,您可以使用PHP语言的现有功能

try {
  print($wrapper->field_property_sample->value());
}
catch (EntityMetadataWrapperException $e) {
  // Recover
}
Run Code Online (Sandbox Code Playgroud)

或者,因为EntityMetadataWrapper实现,__isset()您可以使用:

print isset($wrapper->field_property_sample) ? $wrapper->field_property_sample->value() : '';
Run Code Online (Sandbox Code Playgroud)

  • 多次尝试,即使使用isset()调用,它仍然会抛出EntityMetadataWrapperException.还有什么想法吗? (2认同)

laz*_*tem 5

参考Clive的答案,您可以这样使用__isset()

print ($wrapper->__isset('field_property_sample') ? $wrapper->field_property_sample->value() : '';
Run Code Online (Sandbox Code Playgroud)

  • 最好使用isset($ wrapper-> field_property_sample)而不是直接使用魔术方法__isset。如果实现__isset的方式发生了任何变化,则只需调用isset()即可继续以相同的方式工作。 (2认同)