phpsymfonysonata-admin

How to add a global action in Sonata Admin?


Well, I have a fairly basic problem with Sonata Admin in my Symfony2 project.

I have a "products" list view with every product sold on my web store. On the top right "actions" menu, I have the default actions, with a single action named "Add new".

List view in sonata admin

I just want to add more actions next to "Add new": custom actions like "remove promo prices from all products", or "remove all products evaluations".

I don't want a "batch" action, I want a "global" action leading to a custom DB query.

All I find in the doc is related to batch actions or "single line action". Is there a way to do what I want ?

Thank you for your help !


Solution

  • Create and configure a custom admin extension and override the configureActionButtons(AdminInterface $admin, $list, $action, $object) method to add custom actions:

    use Sonata\AdminBundle\Admin\AdminExtension;
    use Sonata\AdminBundle\Admin\AdminInterface;
    use Sonata\AdminBundle\Route\RouteCollection;
    
    class CustomGlobalActionsExtension extends AdminExtension
    {
        public function configureActionButtons(AdminInterface $admin, $list, $action, $object)
        {
            return array_merge($list, [
                ['template' => 'admin/custom_action.html.twig']
            ]);
        }
    
        public function configureRoutes(AdminInterface $admin, RouteCollection $collection)
        {
            $collection->add('custom_action', $admin->getRouterIdParameter().'/custom_action');
        }
    }
    
    {# app/Resources/views/admin/custom_action.html.twig #}
    <a class="btn btn-sm" href="{{ admin.generateObjectUrl('custom_action', object) }}">Custom Action</a>
    

    See also https://sonata-project.org/bundles/admin/2-3/doc/cookbook/recipe_custom_action.html