As an example, we will implement the display of an image thumbnail.
In my case, the coverMedia field is a relationship to Media from the Sonata Media Bundle.
1. Custom table cell template for the list view
Sonata allows you to set a custom template for list views using the template option:template => path to the file in the templates directory
List table cells are rendered based on: base_list_field.html.twigvendor/sonata-project/admin-bundle/src/Resources/views/CRUD/base_list_field.html.twig
The part we want to override is the field block. The content of the coverMedia field will be available in the Twig template via the value variable.
src/Admin/BookAdmin.php
protected function configureListFields(ListMapper $list): void
{
$list
->add('coverMedia', null, [
'label' => 'book.field.cover_media',
'template' => 'admin/common/list/media_image.html.twig',
])
templates/admin/common/list/media_image.html.twig
{% extends get_admin_template('base_list_field', admin.code) %}
{% block field %}
{{ value }}
{% endblock %}Let’s add the image display.
templates/admin/common/list/media_image.html.twig
{% extends get_admin_template('base_list_field', admin.code) %}
{% block field %}
{% if value is not empty %}
{{ sonata_thumbnail(value, 'small') }}
{% endif %}
{% endblock %}2. Passing parameters to the template
Let’s pass some example additional parameters. While they can be added in the standard way, Sonata does not pass them directly as Twig variables, instead, they are all stored within field_description.options.
They can be retrieved as follows:field_description.option('option_name', 'default_value')
src/Admin/BookAdmin.php
protected function configureListFields(ListMapper $list): void
{
$list
->add('coverMedia', null, [
'label' => 'book.field.cover_media',
'template' => 'admin/common/list/media_image.html.twig',
'preview_format' => 'small',
'preview_options' => [
'width'=> 190,
],
])templates/admin/common/list/media_image.html.twig
{% extends get_admin_template('base_list_field', admin.code) %}
{% block field %}
{% if value is not empty %}
{{ sonata_thumbnail(
value,
field_description.option('preview_format', 'small'),
field_description.option('preview_options', [])
) }}
{% endif %}
{% endblock %}Throughout the template, we have access to:value – our valueobject – the entire objectadmin – the admin object

Leave a Reply