When should Doctrine filters be disabled in the SonataAdmin workflow?

I'm sure this is a common ask, I need softdeletable and similar filters off in SonataAdmin, until now I've been doing:

use SonataAdminBundleAdminAdmin as BaseAdmin;

class Admin extends BaseAdmin
{
    /**
     * {@inheritdoc}
     */
    public function configure()
    {
        /**
         * This executes everywhere in the admin and disables softdelete for everything, if you need something cleverer this should be rethought.
         */
        $filters = $this->getModelManager()->getEntityManager($this->getClass())->getFilters();

        if (array_key_exists('approvable', $filters->getEnabledFilters())) {
            $filters->disable('approvable');
        }

        if (array_key_exists('softdeleteable', $filters->getEnabledFilters())) {
            $filters->disable('softdeleteable');
        }
    }
}

Which causes a number of problems, one, it needs the conditionals because the admin classes are configured twice, once to build the nav, and again to build interfaces, two, the admin classes are instantiated frontend on a cold (APC maybe?) cache, which is pretty uncool.

Where are you meant to put this logic?


You can use a Event Listener. For example:

Service:

filter.configurator:
class: AppBundleFilterConfigurator
arguments: ["@doctrine.orm.entity_manager"]
tags:
    - { name: kernel.event_listener, event: kernel.controller }

Listener class:

namespace AppBundleFilter;

use DoctrineBundleDoctrineBundleRegistry;
use DoctrineORMEntityManagerInterface;
use SonataAdminBundleControllerCoreController;
use SonataAdminBundleControllerCRUDController;
use SonataAdminBundleControllerHelperController;
use SymfonyComponentHttpKernelEventFilterControllerEvent;

/**
 * Class Configurator
 *
 * @author Andrey Nilov <nilov@glavweb.ru>
 */
class Configurator
{
    /**
     * @var Registry
     */
    private $em;

    /**
     * @param EntityManagerInterface $em
     */
    public function __construct(EntityManagerInterface $em)
    {
        $this->em = $em;
    }

    /**
     * onKernelRequest
     */
    public function onKernelController(FilterControllerEvent $event)
    {
        $controller = $event->getController();
        $controllerClass = $controller[0];

        $isAdminController =
            $controllerClass instanceof CRUDController ||
            $controllerClass instanceof CoreController ||
            $controllerClass instanceof HelperController
        ;

        if ($isAdminController) {
            $this->em->getFilters()->disable('softdeleteable');
        }
    }
}
链接地址: http://www.djcxy.com/p/65026.html

上一篇: Softdeletable行为,真正删除实体

下一篇: 什么时候应该在SonataAdmin工作流程中禁用Doctrine过滤器?