Using custom fields of type media
After you have added a custom field of type media, with the administration or via plugin, you can assign media objects to the different entities. This is often used for products to add more images to the product detail page. If you want to learn more about custom fields you might want to take a look at this guide: Adding custom fields.

Overview

In the product detail page template, the key page.product.translated.customFields.xxx with the xxx, which is replaced with the corresponding custom field, contains the UUID of the media. Now the ID has just to be resolved with the function searchMedia:
platform/src/Core/Framework/Adapter/Twig/Extension/MediaExtension.php
1
public function searchMedia(array $ids, Context $context): MediaCollection { ... }
Copied!
This function resolves out the corresponding media objects for the given IDs in order to continue working with them afterwards. Here is an example with a custom field (custom_sports_media_id) on the product detail page:
<plugin root>/src/Resources/views/storefront/page/content/product-detail.html.twig
1
{% sw_extends '@Storefront/storefront/page/product-detail/index.html.twig' %}
2
​
3
{% block page_product_detail_media %}
4
{# simplify ID access #}
5
{% set sportsMediaId = page.product.translated.customFields.custom_sports_media_id %}
6
​
7
{# fetch media as batch - optimized for performance #}
8
{% set mediaCollection = searchMedia([sportsMediaId], context.context) %}
9
​
10
{# extract single media object #}
11
{% set sportsMedia = mediaCollection.get(sportsMediaId) %}
12
​
13
{{ dump (sportsMedia) }}
14
{% endblock %}
Copied!

Avoid loops

This function performs a query against the database on every invocation and should therefore not be used within a loop. To resolve multiple ID's at once just pass it an array of ID's instead.
To read the media objects within the product listing we recommend the following procedure:
<plugin root>/src/Resources/views/storefront/component/product/listing.html.twig
1
{% sw_extends '@Storefront/storefront/component/product/listing.html.twig' %}
2
​
3
{% block element_product_listing_col %}
4
{# initial ID array #}
5
{% set sportsMediaIds = [] %}
6
​
7
{% for product in searchResult %}
8
{# simplify ID access #}
9
{% set sportsMediaId = product.translated.customFields.custom_sports_media_id %}
10
​
11
{# merge IDs to a single array #}
12
{% set sportsMediaIds = sportsMediaIds|merge([sportsMediaId]) %}
13
{% endfor %}
14
​
15
{# do a single fetch from database #}
16
{% set mediaCollection = searchMedia(sportsMediaIds, context.context) %}
17
​
18
{% for product in searchResult %}
19
{# simplify ID access #}
20
{% set sportsMediaId = product.translated.customFields.custom_sports_media_id %}
21
​
22
{# get access to media of product #}
23
{% set sportsMedia = mediaCollection.get(sportsMediaId) %}
24
​
25
{{ dump(sportsMedia) }}
26
{% endfor %}
27
{% endblock %}
Copied!
Last modified 5mo ago
Copy link