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

試著忘記壹切 提交于 2021-01-28 08:03:55

问题


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?


回答1:


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())
        ;
}]),


来源:https://stackoverflow.com/questions/63439187/easyadmin-3-limit-data-to-the-logged-in-user-still-shows-other-data-in-form-dro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!