Question

I want to systematically filter doctrine queries so I don't have to specify some data any time I use a repository.

For instance, I have one single database where entities are binded to clients. I want to be able to retrieve my entities whether I'm this or that client transparently like:

$entities = $em->getRepository('ns:Entity')->findAll();

So I used a filter which I would like to bo something like:

public function addFilterConstraint(ClassMetadata $targetEntity, $targetTableAlias)
{
    $id = $this->get('session')->get('current_client_id');

    return sprintf("$targetTableAlias.client_id=%d", $id);
}

The problem is, filter operate at sql level, so it's not container aware, so I can't access session or services (which may be wrong).

Any idea how to deal with dynamic filtering ?

I tried with custom repositories, but same problem happens, plus I'd have to duplicate functions for every entity.

[EDIT]

You can resolve this passing a parameter to the filter:

$filter = $this->doctrine->getManager()->getFilters()->enable('my_filter');
$filter->setParameter('current_fair_id', $currentFair->getId());

Then all that's left to do is getting the parameter within the addFilterConstraint method of your QueryFilter inherited class:

$value = $this->getParameter('current_fair_id');
Was it helpful?

Solution

I can't show you a working example for symfony2 but in zf2 here: Setup Doctrine 2 filters in Zend Framework 2

Anyway this should be portable to symfony2 by finding the place in your code where you enable the filter. This is the place where you can also set / add parameters like you session_id:

$id = $this->get('session')->get('current_client_id');
$filter = $entityManager->getFilters()->enable('your_filter_class_name');
$filter->setParameter('current_client_id', $id);

Please see Doctrine docs here:

Parameters for the query should be set on the filter object by SQLFilter#setParameter(). Only parameters set via this function can be used in filters. The SQLFilter#getParameter() function takes care of the proper quoting of parameters.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top