如何在 Sonata Admin 中添加一个全局动作?

How to add a global action in Sonata Admin?

好吧,我的 Symfony2 项目中的 Sonata Admin 有一个相当基本的问题。

我有一个 "products" 列表视图,其中包含我的网上商店中出售的所有产品。在右上角 "actions" 菜单中,我有默认操作,其中一个操作名为 "Add new".

我只想在 "Add new" 旁边添加更多操作:自定义操作,例如 "remove promo prices from all products" 或 "remove all products evaluations"。

我不想要 "batch" 操作,我想要 "global" 操作导致自定义数据库查询。

我在文档中找到的所有内容都与批处理操作或 "single line action" 有关。有没有办法做我想做的事?

感谢您的帮助!

Create and configure a custom admin extension 并覆盖 configureActionButtons(AdminInterface $admin, $list, $action, $object) 方法以添加自定义操作:

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>

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

语法有点变化,调用父方法很重要:

/**
 * @param $action
 * @param null|object $object
 * @return array
 */
public function configureActionButtons($action, $object = null)
{
    $buttonList = parent::configureActionButtons($action, $object);
    $buttonList['create_custom'] = [
        'template' => 'admin/action/button.html.twig'
    ];

    unset($buttonList['not_wanted']);

    return $buttonList;
}