1

I'm using the media entity from Drupal core together with the media library, to handle media on my site.

I have Remote Video and Image with crop media types. I'm using the crop and image_widget_crop modules to manually crop images on my site.

Remote video supports YouTube and Vimeo.

Right now the thumbnail is automatically generated, but I want to be able to upload a custom thumbnail. If no custom thumbnail is provided, it will just use the auto generated one.

I found this guide, but it is for Drupal 7.

Has anyone done something similar to this in Drupal 8?

4
  • Is this the thumbnail used in the media library module? As I'd guess what you could do is add a new image field to the remote video media type. Then just change go into "manage display" and change the media library display to show that instead of the thumbnail. You could do that for any other display e.e.g the default too
    – Leigh
    Sep 12, 2019 at 15:07
  • Yes, the only problem is that it has to fallback to the auto generated thumbnail if a custom thumbnail has not been uploaded.
    – user72672
    Sep 12, 2019 at 15:08
  • Oh yeah sorry I forgot about that. You could potentially create a new FieldFormatter that was essentially a copy of the standard Image one (api.drupal.org/api/drupal/…) but it would check for the custom image by using $items->getParent() to get the parent entity with all its fields
    – Leigh
    Sep 12, 2019 at 15:37
  • @Leigh Thanks for the tip I actually found a solution myself :)
    – user72672
    Sep 12, 2019 at 16:15

2 Answers 2

5

I solved the problem by adding an image field on the remote video media entity and then altering the media entity on presave, like this:

/**
 * Implements hook_entity_presave().
 */
function MY_MODULE_entity_presave(Drupal\Core\Entity\EntityInterface $entity) {
  if ($entity->getEntityTypeId() == 'media' && isset($entity->field_media_image->entity)) {
    $entity->thumbnail->target_id = $entity->field_media_image->target_id;
  }
}

The image field is called field_media_image.

2
  • Awesome, works like a charm. THX!
    – zsd
    Feb 7, 2023 at 10:52
  • 1
    You can use the more specific MY_MODULE_media_presave hook, and you don't have to check the entity type.
    – Tim
    Mar 3, 2023 at 10:20
0

I did a similar solution to the preprocess above in twig. I added a new (media) image field to my remote video entity, and a view mode for my remote video entity called "small". The view mode has two fields, the new image field, and the thumbnail field.

Twig file is: media--remote-video--small.html.twig

With content:

{%
set classes = [
'media',
'media--type-' ~ media.bundle()|clean_class,
]
%}

<div{{ attributes.addClass(classes) }}>

  {% if media.field_alternative_thumb is not empty %}
    {{content.alternative_thumb}}
  {% else %}
    {{content}}
  {% endif %}
</div>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.