Search code examples
symfony5easyadmin3

easyadmin 3.3 groupby in AssociationField


I'm using symfony 5.1 and easyadmin 3.3, I know I'm not updated but now I can't update right now.

I have a relationship 1:m between Product and Dealer, in the ProductCrudController I have a Dealer as a AssociationField and I have a query_builder to show only a specific group of Dealer what they are showing in a select2 field. The Dealers can be a diferent zones and I would like group those Dealers by zone.

I have looked at several articles but anything like this.

This is my code, but I don't know how to group them.

// in ProductCrudController
$fields[] = AssociationField::new('dealer')
        ->setFormTypeOptions([
        'query_builder' => function (DealerRepository $repository) {
          return $repository->findByDepartament($this->getUser());
        },
      ])

Solution

  • I don't know if it's really the best way to resolve this but at least it worked for me. I didn't use 'AssociationField' like I'd though previously, I get the array then group by zone and use a 'ChoiceField'.

    This is my code:

    $repository = $this->getEntityManager()->getRepository(Dealer::class);
    $result = $repository->findByDepartament($this->getUser());
    $choice = [];
    
    foreach ($result as $d){
      $choice[$d->getZone()->getName()][$d->getName()] = $d;
    }
    
    $fields[] = ChoiceField::new('dealer')
        ->setChoices($choice);