Field API examples for Drupal 8

Last updated on 17/11/2017

Get the value of a single reference field.

/**
 * Get the value of a single reference field.
 *
 * @param \Drupal\Core\Entity\EntityInterface $entity
 * @param $fieldName
 *   Field name to get value for.
 * @param bool $getId
 *   Weather to return the Entity ID or the Entity object.
 * @return \Drupal\Core\Entity\Entity|int|NULL
 */
public function getSingleReferenceFieldValue(EntityInterface $entity, $fieldName, $getId = FALSE) {
  if ($entity->hasField($fieldName)) {
    $field = $entity->get($fieldName);
    if (!$field->isEmpty()) {
      $fetchedEntity = $field->first()
        ->get('entity')
        ->getTarget()
        ->getValue();
      return $getId ? $fetchedEntity->id() : $fetchedEntity;
    }
  }
  return NULL;
}

To be completed...