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_field = $node->field_paragraph_example;
 
  // Returns early if the field does not exist;
  if (is_null($paragraph_field)) {
    return;
  }
 
  $paragraph = $paragraph_field->entity;
 
  // Returns early if the field is empty.
  if (is_null($paragraph)) {
    return;
  }
 
  $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_example_text_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->getParentEntity();
// ...

If you have installed the Devel module and configured it to use Kint, then seeing all the methods on an entity can be done by combining dpm() and get_class_methods(), as follows:

dpm(get_class_methods($paragraph));

Article Type

General