0

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.

Dhia Djobbi
  • 1,176
  • 2
  • 15
  • 35
MaxPower
  • 45
  • 1
  • 12

1 Answers1

2

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)')
      ;
  })
  ;
  // ...
}
Flash
  • 1,101
  • 1
  • 9
  • 13