Search code examples
symfonyeasyadmineasyadmin3

Symfony 5 / Easy Admin 3 - FormBuilder added field not displaying appropiate input


I am building a form using Easy Admin's FormBuilder. My goal is to have an AssociationField which represents a OneToMany relationship, for example, to assign multiple products to a shop. Additionally, I only want some filtered products to be listed, so I overrode the createEditFormBuilder method in the CrudController, I used this question as reference, and this is the code for the overridden function :

    public function createEditFormBuilder(EntityDto $entityDto, KeyValueStore $formOptions, AdminContext $context): FormBuilderInterface
    {
        $formBuilder = parent::createEditFormBuilder($entityDto, $formOptions, $context);

        $filteredProducts = $context->getEntity()->getInstance()->getFilteredProducts();

        $formBuilder->add('products', EntityType::class, ['class' => 'App\Entity\Product', 'choices' => $filteredProducts, 'multiple' => true]);

        return $formBuilder;
    }

I expected an Association field as the ones configured in the configureFields() function, however, the displayed field doesn't allow text search or autocomplete features, plus has incorrect height.

Expected:

enter image description here

Actual:

enter image description here

I tried to change the second argument in the $formBuilder->Add() function, but all specific EasyAdmin types threw errors.

UPDATE: I also tried using EasyAdmin's CrudFormType instead of EntityType, which doesn't support the 'choice' parameter. Still, the result was the same.


Solution

  • There is setQueryBuilder on the field, you can use it for filtering entities like this

    <?php
    
    // ...
    public function configureFields(string $pageName): iterable
    {
      // ...
      yield new AssociationField::new('products')->setQueryBuilder(function($queryBuilder) {
          $queryBuilder
            ->andWhere('entity.id IN (1,2,3)')
          ;
      })
      ;
      // ...
    }