Search code examples
symfonysymfony-sonata

Symfony SonataAdmin Templates


I am trying to modify the SonataAdmin templates. I have an Image entity that has a path property. I created an ImageAdmin class and this is integrated into sonataAdmin. I would like to modify the admin-list-view to wrap the path in an img tag so that the image is actually displayed. Does anyone know how I can do this?

Thanks!


Solution

  • There are 2 ways to use your own templates.

    In the config file:

    sonata_doctrine_orm_admin:
        entity_manager: 
    
        templates:
            form:
                - SonataDoctrineORMAdminBundle:Form:form_admin_fields.html.twig
            filter:
                - SonataDoctrineORMAdminBundle:Form:filter_admin_fields.html.twig
            types:
                list:
                   ...
    
                show:
                    ...
                    image: YourBundle:YourFolder:yourtemplate.html.twig
    

    and in the field definition file:

    <?php
                namespace ...;
    
                use Sonata\AdminBundle\Admin\Admin;
                use Sonata\AdminBundle\Form\FormMapper;
                use Sonata\AdminBundle\Datagrid\DatagridMapper;
                use Sonata\AdminBundle\Datagrid\ListMapper;
                use Sonata\AdminBundle\Show\ShowMapper;
    
                class ImageAdmin extends Admin
                {
                    protected function configureShowField(ShowMapper $showMapper)
                    {
                        $showMapper
                            ...
                            ->add('image', 'image')
                            ...
                        ;
                    }
                }
            ?>
    

    OR the 2nd way:

        <?php
            namespace ...;
    
            use Sonata\AdminBundle\Admin\Admin;
            use Sonata\AdminBundle\Form\FormMapper;
            use Sonata\AdminBundle\Datagrid\DatagridMapper;
            use Sonata\AdminBundle\Datagrid\ListMapper;
            use Sonata\AdminBundle\Show\ShowMapper;
    
            class ImageAdmin extends Admin
            {
                protected function configureShowField(ShowMapper $showMapper)
                {
                    $showMapper
                        ...
                        ->add('image', 'string', array('template' => 'YourBundle:YourFolder:yourtemplate.html.twig'))
                        ...
                    ;
                }
            }
        ?>
    

    And then copy the code below to your template:

    {% extends 'SonataAdminBundle:CRUD:base_show_field.html.twig' %}
    
    
    {% block field %}
        <img src="{{ asset('uploads/media/') }}{{ value|nl2br }}"/>
    {% endblock %}