Jim Panse Jim Panse - 1 year ago 129
Twig Question

change row color in sonata admin bundle dependent on a value of a field

I have the sonata admin bundle and can't figure out, how to change a styling dependent on a field value in a form template.

for example field difficulty ... the higher the difficulty value is, the more red colored the record row should be ...

How can i do this? I spend hours to understand the twig templates in sonata, but the more i read this templates, the more i get confused.

There are block calls amongst a template and its not possible to figure out, where this calls leading to or come from.

I use symfony 2 with Sonata Admin Bundle.


Answer Source

Make your own template wich extends SonataAdminBundle:CRUD:base_edit.html.twig and either override the $templates property of your admin class or pass it in your admin service declaration like so:

        class: Librinfo\CRMBundle\Admin\OrganismAdmin
        arguments: [~, Librinfo\CRMBundle\Entity\Organism, LibrinfoCRMBundle:OrganismAdmin]
            -   name: sonata.admin
                manager_type: orm
                group: Customers Relationship Management
                label: librinfo.crm.organism_admin.label
                label_translator_strategy: blast_core.label.strategy.librinfo
            - [ setTemplate, [edit, LibrinfoCRMBundle:OrganismAdmin:edit.html.twig]] #set a custom edit template
            - [ setTemplate, [show, LibrinfoCRMBundle:OrganismAdmin:show.html.twig]] #sets a custom show template

your custom template will need to override the default sonata template for example:

{% extends 'SonataAdminBundle:CRUD:base_edit.html.twig' %}

{% block form %}
    {# your custom code #}
{% endblock %}

If you don't know wich block or wich template to extend tell me wich view you want to customize (list, edit, show) but probably all of them.

Then to retrieve the field that you want or anything you can use the

{% dump %}

to dump all variables of the template in the profiler or

{% dump(myVar) %} to dump a specific variable


base_template is a variable passed from the controller that contains the name of the template.

If you look closely, all of these templates ultimately extend the base_template variable that’s passed from the controller. This variable will always take the value of one of the above mentioned global templates, and this is how changes made to those files affect all the SonataAdminBundle interface.


If you dump the base_template variable you'll know wich template is extended.

For the parentForm block just look above:

{% use 'SonataAdminBundle:CRUD:base_edit_form.html.twig' with form as parentForm %}

This line imports SonataAdminBundle:CRUD:base_edit_form.html.twig form block aliased as parentForm.

So {{ block('parentForm') }} is a call to render a form block from SonataAdminBundle:CRUD:base_edit_form.html.twig.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download