Sonata project, Symfony2, Webdevelopment

Render a preview image in SonataAdminBundle

For those of you that are using the SonataAdminBundle and SonataMediaBundle to generate a CMS for your website, you might have wondered how to show a preview of your freshly uploaded image. Well, here’s how to do it.

So first, here’s a the configuration of my formMapper in my admin class:

[sourcecode]
protected function configureFormFields(FormMapper $formMapper)
{
$formMapper
->add(‘title’, null, array(‘attr’ => array(‘title’ => ‘contentItem-title’)))
->add(‘description’)
->add(‘deviceClass’)
->add(‘image’, ‘sonata_type_model_list’, array(
‘required’ => false
), array(
‘link_parameters’ => array(
‘context’ => ‘default’,
‘provider’ => ‘sonata.media.provider.image’
)
)
)
[/sourcecode]

Without going into too many details about the Sonata media bundle, the above configuration will show a nice field with buttons for uploading an image. But instead of showing the uploaded image, it shows only the image name. Now, to show the image do the following:

1. Copy the file Sonata/AdminBundle/Resources/views/Helper/short-object-description.html.twig to a place in your own bundle. Preferably somewhere in the Resources/views directory.

2. Next add some statements so that if an image is provided you will show it:

[sourcecode]

<span>
{% if object.providerName is defined and object.providerName == ‘sonata.media.provider.image’ %}
<a href="{{ url }}" target="new">{% media object, ‘reference’ %}</a>
{% else %}
<a href="{{ url }}" target="new">{{ description }}</a>
{% endif %}
</span>

[/sourcecode]

3.  Last thing to do is to tell Sonata that you want to override the default template for your own. You do this in the config.yml of your project by adding the following line:

[sourcecode]
sonata_admin:
templates:
short_object_description: YourBundle:Admin:short-object-description.html.twig
[/sourcecode]

This should show you the original image in the box next to the buttons. Naturally you can also show a thumbnail by changing the reference parameter in the template.