0

I have three content types (A,B,C). A and B have title, author, and field_version (a custom field), while C doesn't have field_version. Let's assume I have a method that gets the version value from a node. (The $node parameter is an entity object.)

function getLatestVersion($node) {
   $version = $node->get('field_version'); //for A, B is OK, but for C - field_version is unknown
}

How can I check the field exists for the node passed as argument without comparing the node type with an hard-coded list?

1
  • if (!empty($node->get('field_version'))) { $version = $no...
    – No Sssweat
    Commented Jun 9, 2020 at 9:21

1 Answer 1

2

For nodes, like for every content entity, you can use code similar to the following one to check if a Field API field(*) exists.

if ($node->hasField('field_version')) {
  // The node has that field; access it with $node->hasField('field_version').
}

A more generic code that would work for either Field API fields or non-field properties would be similar to the following one.

if (isset($node->field_version)) {
  // The node has that field/property; access it with $node->field_version.
}

* I am using the terminology used in a comment for code in ContentEntityBase::__isset().

// "Official" Field API fields are always set. For non-field properties,
// check the internal values.
return $this->hasField($name) ? TRUE : isset($this->values[$name]);

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.