1

I have an image file that I am viewing programmatically. When I set the image format to "responsive image" in file display settings, it breaks with an error

Error: Call to a member function getMetadata() on null in file_entity_preprocess_responsive_image_formatter() (line 488 of modules/contrib/file_entity/file_entity.module).

My render code:

$file = File::load($fid);
$build = [];
if ($file) {
  $view_builder = \Drupal::entityTypeManager()->getViewBuilder($file->getEntityTypeId());
  $build = $view_builder->view($file, 'embed');
}

"embed" is the file view mode that sets the image to display as responsive.

There seems to be missing the "item" in the build array resulting from this, which is expected to be a fielditem. Am I doing something wrong?

  • 2
    Core doesn't support view modes for files, so this is probably an issue in a contrib module. If this is the File Entity module then better use the new Media entity now in core. – 4k4 Jan 8 at 9:28
  • Yes - will do a workaround for now. Will get the style from the view mode and programmatically render with that responsive image style. – Alexei Rayu Jan 8 at 10:01
1

This is not a proper answer, but a workaround in case someone else has this issue: detect if a responsive style is used, load it, and apply via theme layer (the style name is hard-coded to be "embed"):

if ($file) {
  $view_mode = \Drupal::entityTypeManager()
     ->getStorage('entity_view_display')
     ->load('file.' . $file->bundle() . '.embed');
  $content = $view_mode->get('content');

  // Responsive.
  if (!empty($content['uri']['settings']['responsive_image_style'])) {
    $build = [
      '#theme' => 'responsive_image',
      '#responsive_image_style_id' => $content['uri']['settings']['responsive_image_style'],
      '#uri' => $file->getFileUri(),
    ];
  }

  // Non responsive.
  else {
    $view_builder = \Drupal::entityTypeManager()->getViewBuilder($file->getEntityTypeId());
    $build = $view_builder->view($file, 'embed');
  }
}

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.