I have a preprocess function that I am using to grab one of 3 profile images. Basically we're replacing a couple stand-alone image fields with a media library reference field. The goal is to display the media library image if it is populated at a particular style (called '65x65') or fall back to other stand-alone legacy image fields if it is not populated.
I'm having a heck of a time building the media library image url. I have tried quite a few things based on this discussion and this discussion and others. The image field on the image media type is called field_media_image (screenshot). I'm not sure if it's useful to post my half-baked code attempts so I will leave the parts that I know are working.
foreach ($block->field_block_contributors->referencedEntities() as $contributor) {
# prefer the media library reference profile image if it exists
if (!$contributor->field_profile_image->isEmpty()) { # check if there is a media library profile image
$my_profile_image = $contributor->get('field_profile_image')->referencedEntities(); # seems to load this field ok
if (!empty($my_profile_image)) {
// kint($my_profile_image);
# load a media library image using the '65x65' image style
// $styled_image_url = ??????
}
} elseif (!$contributor->field_user_image->isEmpty()) { # or fall back to one of two legacy image fields. This part works
$styled_image_url = ImageStyle::load('65x65')->buildUrl($contributor->field_user_image->entity->getFileUri());
} elseif (!$contributor->field_speaker_image->isEmpty()) {
$styled_image_url = ImageStyle::load('65x65')->buildUrl($contributor->field_speaker_image->entity->getFileUri());
} else {
$styled_image_url = '';
}
$variables['profiles'][] = [
'title' => $contributor->field_user_title->value,
'link' => "/user/" . $contributor->uid->value,
'image' => ['src' => $styled_image_url, 'attributes' => $contributor->field_user_image->value],
'name' => $contributor->field_user_first_name->value . " " . $contributor->field_user_last_name->value,
];
}
PS. Bonus beer for anyone who knows off the top of their heads how I can link to the user's name instead of their user id # ( the line 'link' => "/user/" . $contributor->uid->value, ) Thanks!!!