2

I have a paragraph type with a media entity reference field field_paragraph_image_ref.

I need to modify the media Twig template depending on a field value of the parent, which is a paragraph entity.

There are ways to get the parent entity of a paragraph, but media entities don't have a getParentEntity() method. Also with _referringItem I am unable to get up to the parent paragraph itself.

How can I get the field value from the parent paragraph in the media preprocess?

/**
 * Implements hook_preprocess_HOOK().
 */
function hook_preprocess_media__picture__image_without_link(&$variables) {
  $media = $variables['elements']['#media'];
  // A method to get the parent entity, that I cannot find in
  // var_dump(get_class_methods($media));
  // and finally get a field value from the parent paragraph entity.
}
1
  • 3
    Does this answer your question? Preprocess image: how to get parent entity? - while this question handles images, it this the same scheme, look at the code line with _referringItem and look out for caching issues.
    – Hudri
    Commented Dec 1, 2020 at 13:58

2 Answers 2

2

I passed the parent entity "manually" to the media instance from one hook to the other.

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME_preprocess_paragraph__picture(&$variables) {
  $paragraph = $variables['paragraph'];

  $media = $paragraph->field_paragraph_image_ref->entity;

  // Storing the parent paragraph as an attribute of the media instance.
  $media->parent_paragraph = $paragraph;
}

/**
 * Implements hook_preprocess_HOOK().
 */
function MYTHEME_preprocess_media__picture__image_without_link(&$variables) {
  $media = $variables['elements']['#media'];

  if (isset($media->parent_paragraph)) {
    $paragraph = $media->parent_paragraph;

    // Now the field of the paragraph can be accessed and pass to the media
    // Twig template.
    $variables['my_field'] = $paragraph->my_field;
  }
}
-1

i have ended up doing:

function hook_preprocess_media__picture__image_without_link(array &$variables) {
   $media = $variables['elements']['#media'];
   $parent = Drupal::entityTypeManager()->getStorage('paragraph')->loadByProperties([
    'field_paragraph_image_ref' => $media->id()
  ]);
   $parent = reset($parent);
   var_dump($parent->get("field_paragraph_image_link_page")->getValue();
}
1
  • not that good because it would load all paragraphs that have that media id for entity ref
    – Matoeil
    Commented Dec 1, 2020 at 16:35

Not the answer you're looking for? Browse other questions tagged or ask your own question.