Search code examples
phpsymfonyeasyadmin

EasyAdmin 3: limit data to the logged-in user still shows other data in form dropdowns


I'm using Symfony 5.

I want every logged in user to have it's own space in EasyAdmin 3, so no user will see records of other users. I store the user with every table in the database.

For simple list views, I managed to get this to work using a extension of the AbstractCrudController:

<?php
namespace App\Controller\Admin;

use Doctrine\ORM\QueryBuilder;
use EasyCorp\Bundle\EasyAdminBundle\Collection\FieldCollection;
use EasyCorp\Bundle\EasyAdminBundle\Collection\FilterCollection;
use EasyCorp\Bundle\EasyAdminBundle\Controller\AbstractCrudController;
use EasyCorp\Bundle\EasyAdminBundle\Dto\EntityDto;
use EasyCorp\Bundle\EasyAdminBundle\Dto\SearchDto;
use EasyCorp\Bundle\EasyAdminBundle\Orm\EntityRepository;

abstract class CustomCrudController extends AbstractCrudController
{
    public function createIndexQueryBuilder(SearchDto $searchDto, EntityDto $entityDto, FieldCollection $fields, FilterCollection $filters): QueryBuilder
    {
        $qb = $this->get(EntityRepository::class)->createQueryBuilder($searchDto, $entityDto, $fields, $filters);
        $qb->andWhere('entity.user = :user');
        $qb->setParameter('user', $this->getUser());
        return $qb;
    }
}

I also store/check the user through a EventSubscriber.

Problem is, some forms have a relation to another Entity(like AssociationField::new('food')) and when filling the dropdowns it ignores my new function. So you will see records belonging to another user.

How do I override these dropdowns to also only show data belonging to the current user?


Solution

  • I found the solution: pass a custom query to the underlying EntityType field of Symfony.

    AssociationField::new('food')
        ->setRequired(true)
        ->setFormTypeOptions(['query_builder' => function (EntityRepository $em) {
        return $em->createQueryBuilder('f')
            ->where('f.user = :user')
            ->orderBy('f.title', 'ASC')
            ->setParameter('user', $this->getUser())
            ;
    }]),