Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 988
Oli Avatar asked Oct 26 '25 04:10

Oli


1 Answers

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())
        ;
}]),
like image 85
Oli Avatar answered Oct 28 '25 17:10

Oli



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!