Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony EasyAdminBundle: Filter entities in assotiation field

I have a form with assotation field type (list of related entities).

What I've been trying to achieve is to filter this list on "newAction" form (create new entity).

For example, following screen below:

  1. There is a Survey entity with field "User".
  2. There is Department entity with field "Survey" (@ORM\ManyToOne) where the User choose a survey.

You can see two available surveys but I want to display only the first one, because its User field value is the same as current user.

enter image description here

It is confusing, because I can't find values passed to the Survey field when I debuging.

like image 517
fadehelix Avatar asked Oct 22 '16 22:10

fadehelix


1 Answers

Best way is override default controller and apply query builder for form like this.

YML:-

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

In 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;
    }
}
like image 126
Maya Shah Avatar answered Nov 16 '22 08:11

Maya Shah