How to check if a field exists in Drupal entity

If you are creating a new Drupal 8 theme, and you need to find out if a field exists or not in the node entity then you can use the following “hasField()” Drupal 8 function. It is a good idea to validate the existence before using it to avoid any unexpected error. Please note this method is only available in Drupal 8 and might not work for Drupal 7 theming.

 

Code:

$entity->hasField('fieldName');

 

Drupal API “hasField()” function determines if Drupal entity has a field with a given name or not. It returns a boolean “TRUE” if the given name is found or “FALSE” otherwise.

Check the following example code using Drupal 8 “hasField()” method


/**
 * Get the value of an Entity field.
 *
*/
public function getEntityFieldValue(EntityInterface $entity, $fieldName) {
  if ($entity->hasField($fieldName)) {
    $field = $entity->get($fieldName);
    if (!$field->isEmpty()) {
      $fieldValue = $field->getValue();
      return $fieldValue;
    }
  }
  return NULL;
}

 

// load node entity reference to $node variable
$node = \Drupal\node\Entity\Node::load($nid);

// print title of the node. print($node, “title”);