Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 693
Gintro Avatar asked Nov 30 '22 22:11

Gintro


2 Answers

Looking at the Doctrine code, there are methods to enable and disable filters.

Once you have defined your filter in the config.yml file, you can enable/disable in a controller or service:

// 'status' is the unique name of the filter in the config file
$this->getDoctrine()->getManager()->getFilters()->enable('status');

$this->getDoctrine()->getManager()->getFilters()->disable('status');

Note: this was taken from Symfony 2.3. You would need to test this with previous versions of Symfony/Doctrine.

like image 134
Andrew Avatar answered Dec 04 '22 03:12

Andrew


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.

like image 36
Florian Klein Avatar answered Dec 04 '22 02:12

Florian Klein