How to traverse up and down nested entities in Drupal 8

Sometimes it's necessary to get values from children or parents of an entity. In Drupal 8, like in previous versions, there are hard ways and easy ways to get at this information.

Here's an example of a node preprocess function which traverses down to a paragraph, then to a nested paragraph, then to a term on the nested paragraph, then finally gets the value from a field on the term.

function example_preprocess_node(&$variables) {
  $node = $variables['node'];
  $paragraph = $node->field_paragraph_example->entity;
  $nested_paragraph = $paragraph->field_another_paragraph_ref->entity;
  $term = $nested_paragraph->field_example_term_ref->entity;
  // The following simple syntax works when you just need the first value of the field:
  $textfield_value_on_term = $term->field_exampletext_on_term->value;
// ...

Here's an example, using hook_view_mode_alter(), which traverses up to get the parent that a media entity is attached to:

function example_entity_view_mode_alter(&$view_mode, Drupal\Core\Entity\EntityInterface $entity, $context) {
  if ($entity->getEntityTypeId() === 'media' && $entity->bundle() === 'image') {
    $parent_entity = $entity->_referringItem->getEntity();
// ...

Article Type