Symfony EasyAdminBundle:在assotiation字段中过滤实体

时间:2016-10-22 22:37:47

标签: symfony doctrine-orm entity symfony-forms symfony2-easyadmin

我有一个带有assotation字段类型的表单(相关实体列表)。

我一直想要达到的目的是在" newAction"上过滤此列表。 form(创建新实体)。

例如,在以下屏幕下方:

  1. 有一个调查实体,其中包含字段" User"。
  2. 有部门实体,领域"调查" (@ORM \ ManyToOne)用户选择调查。
  3. 您可以看到两个可用的调查,但我只想显示第一个调查,因为其用户字段值与当前用户相同。

    enter image description here

    令人困惑,因为我在调试时无法找到传递给调查字段的值。

2 个答案:

答案 0 :(得分:4)

最好的方法是覆盖默认控制器并为这样的表单应用查询构建器。

YML: -

easy_admin:
    entities:
        Department:
            class: YourBundle\Entity\Department
            controller: YourBundle\Controller\Admin\Model\DepartmentController

在DepartmentController中: -

<?php

namespace YourBundle\Controller\Admin\Model;

use Doctrine\ORM\EntityRepository;
use Doctrine\ORM\QueryBuilder;
use Symfony\Bridge\Doctrine\Form\Type\EntityType;
use JavierEguiluz\Bundle\EasyAdminBundle\Controller\AdminController;

class DepartmentController extends AdminController
{
    public function createDepartmentEntityFormBuilder($entity, $view)
    {
        $formBuilder = parent::createEntityFormBuilder($entity, $view);

        $user = $this->get('security.token_storage')->getToken()->getUser();

        $formBuilder->add('survey', EntityType::class, [
            'class' => 'YourBundle\Entity\Survey',
            'query_builder' => function (EntityRepository $er) {
                return $er->createQueryBuilder('s')
                    ->where('s.user = :user')
                    ->setParameter('user', $user);
            },
        ]);

        return $formBuilder;
    }
}

答案 1 :(得分:0)

我的解决方案:

$formBuilder = parent::createEntityFormBuilder($entity, $view);
    if (!$this->get('security.authorization_checker')->isGranted('ROLE_SUPER_ADMIN')) {
        $user = $this->get('security.token_storage')->getToken()->getUser();
        $promoter = $this->getDoctrine()
            ->getRepository(Promoter::class)
            ->findByUser($user);
        $queryBuilder = $this->getDoctrine()
            ->getRepository(Customer::class)
            ->getActiveByPromoterQueryBuilder($promoter);
        $formBuilder->add(
            'customers', EntityType::class, [
                'class' => Customer::class,
                'query_builder' => $queryBuilder,
                "attr" => ["class" => "form-control select2", "data-widget" => "select2"],
                'by_reference' => false,
                'multiple' => true,
                'required' => false
            ]
        );
    }
    return $formBuilder;
}

根据'vendor / easycorp / easyadmin-bundle / src / Resources / views / default / includes / _select2_widget.html.twig' 我们只需要添加data-widget属性。