I'm using responsive images (single img
tag with srcset
and sizes
attributes). My content editors can manipulate the displayed size of the image with a custom field on a shared parent entity. Therefore I can't meaningfully use the sizes field from the responsive image module, because my editors can set the image size from 10% of a fixed container up to 100vw on per paragraph level.
I know how to preprocess the sizes attributes, but I don't know how to get to my shared parent entity, which holds the field determining the size of the image's parent container:
function template_preprocess_responsive_image(&$variables) {
// pseudocode: don't know how to this
$imageField = $variables['whatever'];
$parentParagraph = $imageField->getParentMediaEntity()->getParentParagraphEntity();
}
My question is how do I get the parent paragraph entity as written above in pseudocode?
$variables['#item']
? It seems that the viewElements function of the field formatter adds$file->_referringItem
to the render array, which I'd expect to be the parent entity.template_preprocess_responsive_image_formatter()
and you get the field item, which parent is the field and the grandparent is the paragraph.hook_preprocess_responsive_image()
. Usinghook_preprocess_responsive_image_formatter()
and$entity = $variables['item']->getEntity();
I'm getting my media entity. Thanks for your help, I'll post an answer as soon as I have a working code.