0

How do you get the currently chosen image style name from the field format display option?

I can load an image with a given style with the code below, however, the style name (e.g. thumbnail) is hard-coded.

$imageStyle = \Drupal::entityTypeManager()
  ->getStorage('image_style')
  ->load('thumbnail');

I am hoping to get the selected style name dynamically.

MYMODULE.module:

HOOK_preprocess_menu() {

  $imagePath = getUser()['currentUser']->$imageFieldName
    ->entity->uri->value;

  $imageStyleFormatterValue = ???;

  $imageStyle = \Drupal::entityTypeManager()
    ->getStorage('image_style')
    ->load($imageStyleFormatterValue);

  $imageStyleURL = $imageStyle
    ->buildUrl($imagePath);

  $markup = new TranslatableMarkup(
    '<span style="background-image: url(@imageStyleURL);"></span>', [
      '@imageStyleURL' => $imageStyleURL,
    ]
  );

}

For my case, $imageStyleURL will be printed as background-image: url();, so I need to build the path in preprocess.

I've tried going through FieldConfig, ->entity, and FieldStorage, but cannot find the image style value stored anywhere.

  • It's hard to tell by this small code snippet. Normally it is the job of the field formatter to get the formatter options as input and produce the field output. See for example Simple Background image formatter – 4k4 Jun 1 '19 at 8:38
  • Thanks, @4k4, I've added a little more context to my question. I will look at that module but hoping not to have any dependencies. – Prestosaurus Jun 1 '19 at 14:57
0

Field format display options are components of view modes, stored in the config entity EntityViewDisplay.

For example, load the default view mode for the user and extract the configured image style of the user_picture field:

use Drupal\Core\Entity\Entity\EntityViewDisplay;

  $component = EntityViewDisplay::load('user.user.default')->getComponent('user_picture');
  $image_style = $component['settings']['image_style'];

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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