5. Custom form field templates
Adding a ‘template’ parameter to forms is not supported. You need to extend the template in a different way.
The file responsible for rendering form fields is: form_admin_fields.html.twig
vendor/sonata-project/admin-bundle/src/Resources/views/Form/form_admin_fields.html.twig
In our case, we will override the block: sonata_type_model_list_widget
Let’s add a few parameters to control the display.
You can add them in the standard way, however, Sonata does not pass them directly as Twig variables – instead, they are all stored in field_description.options.
They can be retrieved as follows:field_description.option('option_name', 'default_value')
src/Admin/BookAdmin.php
protected function configureFormFields(FormMapper $form): void
{
$form
->add('coverMedia', ModelListType::class, [
'label' => 'book.field.cover_media',
'required' => false,
], [
'preview_image' => true,
'preview_format' => 'small',
'preview_options' => [
'width' => 190,
],
'link_parameters' => [
'context' => 'default',
'provider' => 'sonata.media.provider.image',
],
])Now, we will override the template using the standard Symfony method by placing the template file in the templates/bundles directory.
templates/bundles/SonataAdminBundle/Form/form_admin_fields.html.twig
{% extends '@!SonataAdmin/Form/form_admin_fields.html.twig' %}
{% block sonata_type_model_list_widget %}
{% if value is not empty and sonata_admin.field_description.option('preview_image', false) %}
<div>
{{ sonata_thumbnail(
value,
sonata_admin.field_description.option('preview_format', 'small'),
sonata_admin.field_description.option('preview_options', [])
) }}
</div>
{% endif %}
{{ parent() }}
{% endblock %}Note: use “@!” because we are extending the template, not replacing it entirely (according to Symfony documentation).

Leave a Reply