Search code examples
symfonyconfigurationfilterdoctrine-ormsymfony-2.1

Symfony 2.1 Doctrine filters (enable/disable)


I'm currently implementing Doctrine filters in my Symfony2.1 project with the following setup:

<?php

namespace Acme\Bundle\Entity;

class Article {
    /**
     * @ORM\Column(type="string")
     */
    private $status;
    ...
}

//app/config/config.yml
doctrine:
    orm:
        filters:
            status:
                class:   Acme\Bundle\Filter\StatusFilter
                enabled: false
        ....

//src/Acme/Bundle/Filter/StatusFilter.php
namespace Acme\Bundle\Filter;

use Acme\Bundle\Entity\Status;

class StatusFilter extends SQLFilter {

    public function addFilterConstraint(ClassMetadata $target, $alias)
    {
        $filter =
            $target->reflClass->implementsInterface('Acme\Bundle\Entity\Status')?
                $alias . '.status = ' . Status::PUBLISHED : '';

        return $filter;
    }
}

Where Acme\Bundle\Entity\Status is just an interface.
The code is working as expected when the filter is enabled in config.yml.

The problem is that I cannot retrieve all articles for administration!
Is there a way to enable this filter for a certain bundle?
p.s. I know how to enable and disable the filter with the EntityManager,
I just cannot find the proper place to do it for the frontend Bundle.

my admin section is accessible by route prefix myadmin

www.example.com/myadmin/ -> admin section = disable filter (disabled by default in config) www.example.com/... -> anything else = enable filter.


Solution

  • there is no notion of bundle at Doctrine level. The only way I see would be to detect which controller is used, by parsing its className (reflection, ...) during a kernel.request event, or a kernel.controller event.

    Then, if you detect that your controller is in FrontendBundle, just disable/enable your doctrine filter.

    If you prefer using routing to detect when to disable/enable, just use kernel.request event. You will have access to all request parameters, via $event->getRequest()->attributes->get('_controller') for example.