Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show/hide an action for some rows in Sonata Admin

I am using Sonata Admin. Is it possible to have an action that is only displayed for some of the rows, but not other rows, all in the same list view?

For example, suppose I have a User entity with an "active" field. I would like to show the "remove" action only for inactive users, not for active users. How can I do that?

like image 302
Sander Marechal Avatar asked Oct 21 '25 03:10

Sander Marechal


1 Answers

Yes you can, in your configureListFields admin class action, when adding _action column on $listMapper, you should add template option for delete action, and then you can implement some logic in that template:

$listMapper
    ...
    ->add('_action', 'actions', array(
        'actions' => array(
            'delete' => array(
                'template' => 'YourAdminBundle:List:list_delete_action.html.twig',
            ),
        ),
    ));

And then in list_delete_action.html.twig:

{% if admin.isGranted('DELETE', object) and admin.hasRoute('delete') and not object.isActive %}
<a href="{{ admin.generateObjectUrl('delete', object) }}" class="btn btn-sm btn-default delete_link" title="{{ 'action_delete'|trans({}, 'SonataAdminBundle') }}">
    <i class="glyphicon glyphicon-remove"></i>
    {{ 'action_delete'|trans({}, 'SonataAdminBundle') }}
</a>
{% endif %}

Here in this template you will have object defined, which is entity for each list row, so you can use its getters to get something from you entity. Note that condition in if statement and not object.isActive, so this is where you apply your additional if logic.

like image 78
Dan Mironis Avatar answered Oct 23 '25 17:10

Dan Mironis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!