Skip to main content

How to I access an entity (e.g. node) field in Drupal8

Member for

2 years 7 months
Submitted by admin on
This function access an entity field on a node in Drupal8. It works the following way,
  • Checks to see if node exists
  • Gets the current nodes NID
  • Loads the entity that is attached to the NID
  • Returns the field name of the NID
/**
 * @param $fieldName
 * @return array of Objects
 */
function _access_a_nodes_field($fieldName) {
  if(\Drupal::routeMatch()->getParameter('node')){
    $nid = \Drupal::routeMatch()->getParameter('node');
    $node = \Drupal\node\Entity\Node::load($nid->id());
    return $node->get($fieldName)->getValue();
  }
  return NULL;
}