0

I am having a paragraph with a media entity ref field "field_paragraph_image_ref".

I would need to modiy the media twig template depending on a field value of the parent, which is a paragraph entity.

How can i get the field value from the parent entity in the media preprocess

  function hook_preprocess_media__picture__image_without_link(array &$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
  • 2
    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 Dec 1 '20 at 13:58
0

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 Dec 1 '20 at 16:35
0

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

function hook_preprocess_paragraph__picture(array &$variables) {
  $paragraph = $variables['paragraph'];  
    $mediaId = $paragraph->field_paragraph_image_ref->first()->get("target_id")->getValue();
    $media = Media::load($mediaId);
    //Storing the parent paragraph as an attribute of the media instance
    $media->parent_paragraph = $paragraph;      
  }    
}

function hook_preprocess_media__picture__image_without_link(array &$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;
  }
}

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