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:
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.
It is confusing, because I can't find values passed to the Survey field when I debuging.
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;
}
}