Search code examples
twigshopwareshopware6

How to get media


I'm trying to access the product.media property inside the file /component/product/card/box-standard.html.twig with the following code:

{{ dump(product) }}

But the product.media returns the value null.

The cover image is available as expected with product.cover.media, only the media property has no result.

Do I have to enable it somehow in this twig file that the media is loaded? The goal is to create an image carousel in the image category page to show multiple images, not only the cover image.


Solution

  • The media association is not available in product listings by default, probably because only the cover image is needed and loading unnecessary things degrades performance.

    In your case you need to load that field.

    It is possible with the following approach:

    1. Create a new subscriber for the ProductListingCriteriaEvent
    2. Add the media association

    The subscriber would look similar to this:

    class AddFieldsToProductListingSubscriber implements EventSubscriberInterface {
    
        public static function getSubscribedEvents(): array
        {
            return [
                ProductListingCriteriaEvent::class => 'handleRequest',
            ];
        }
    
    
        public function handleRequest(ProductListingCriteriaEvent $event): void
        {
            $event
                ->getCriteria()
                ->addAssociation('media');
        }
    }
    

    Now

    {{ dump(product.media) }}
    

    will no contain the product media.