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.

1 Answer 1

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)')
      ;
  })
  ;
  // ...
}
Sign up to request clarification or add additional context in comments.

1 Comment

HI do you have any idea to filter CollectionField

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.