0

I'm trying to retrieve a list of objects from database where Entity.user = "current user".

It's a ManyToOne relation between an Entity entity and a User Entity

I tried to use the dql-filter option in the bundle config but couldn't find a parameter variable like we can find in Controller $this->getUser() or in Twig {{app.user}}

I tried to use custom controller but I am confused as the documentation is not very detailed.

dbrumann
  • 16,803
  • 2
  • 42
  • 58
Salim Ben Aissa
  • 435
  • 1
  • 6
  • 21

1 Answers1

0

I would go with a custom controller and overwrite findAll or createListQueryBuilder by always adding a DQL-filter. Something a bit like this:

protected function createListQueryBuilder($entityClass, $sortDirection, $sortField = null, $dqlFilter = null)
{
    if (null === $dqlFilter) {
        $dqlFilter = sprintf('entity.user = %s', $this->getUser()->getId());
    } else {
        $dqlFilter .= sprintf(' AND entity.user = %s', $this->getUser()->getId());
    }

    return parent::createListQueryBuilder($entityClass, $sortDirection, $sortField, $dqlFilter);
}
dbrumann
  • 16,803
  • 2
  • 42
  • 58
  • You might have to fiddle with the property name, but you should get the idea. :) – dbrumann Feb 19 '19 at 20:15
  • If i overwrite the method it won't change globaly for other entities? – Salim Ben Aissa Feb 20 '19 at 00:37
  • No, if you create a custom Controller for an Entity and then assign it to the entity in the configuration (by adding a key controller to the easy_admin.yaml under `entities..controller: `) only this entity will use the controller – dbrumann Feb 20 '19 at 03:45
  • Error in Twig: An exception has been thrown during the rendering of a template ("[Semantical Error] line 0, col 48 near 'user = 1 ORDER': Error: 'user' is not defined."). – Salim Ben Aissa Feb 21 '19 at 09:10
  • 1
    I changed user to entity.user and it works! Update the anwser and i will put it as anwsered. – Salim Ben Aissa Feb 21 '19 at 09:17
  • i have a question it's been one week i'm struggling with newaction i don't know how to get current user id for a field i tried like this ``` - { property: 'idUser', type: 'entity', type_options: { class: 'App\Entity\User', multiple: false }} ``` but in this case i should chose the user. but what exactly i want is to when ever i create an article it should get the current user id and save in my database – Astronaute Jan 02 '20 at 20:50