Search code examples
listsymfonysonata-admin

SonataAdminBundle List different action depending on object attribute


I would like to have different action depending on the object attribute in the List.

My User class has a boolean attribute that I change using a custom action which will have special action such as sending e-mail.

How would I display different action for each object of the list depending on that boolean value ? Like an editable boolean, but for action Buttons. Sorry for my english and many thanks ahead.


Solution

  • You should take a look a this : SonataAdminBundle custom rendering of text fields in list

    Define a new custom type for the list and use it to display your boolean attribute :

    $listMapper
        ->add('my_boolean', 'custom_type')
    

    And your new type template :

    {% extends 'SonataAdminBundle:CRUD:base_list_field.html.twig' %}
    
    {% block field%}
        {% if value == 1 %}
        <a href="...">Change to 0</a>
        {% else %}
        <a href="...">Change to 1</a>
        {% endif %}
    {% endblock %}
    

    If needed, you can access to current object and the admin in your template :

    {% set editable = admin.isGranted('EDIT', object) and object.foo == true %}
    {% if editable == true %}
        {% if value == 1 %}
        <a href="...">Change to 0</a>
        {% else %}
        <a href="...">Change to 1</a>
        {% endif %}
    {% else %}
        {{ value }}
    {% endif %}
    

    For more information on what you can access in the template, take a look at all the default list templates of Sonata :