phpsymfonysymfony5easyadmineasyadmin3

How to list entities in a ChoiceField with EasyAdmin?


I'm trying to set choices in a form using EasyAdmin Bundle. Below is the code inside the controller.

I get this error message: Expected argument of type "App\Entity\Author or null", "int" given at property path "author".

Indeed the ChoiceField returns the Author object's id. How can i transform the id into the object in a fashion manner after the form has been submitted? I am curently using DataTransformers for each field to solve this issue. But this is very heavy as a solution. It means creating 1 DataTransform class for each field.

The documentation doesn't give any clue on how to deal with choices: https://symfony.com/doc/3.x/EasyAdminBundle/fields.html

Thank you.

I'm using EasyAdmin 3 + Symfony 5 on Linux Mint.

In App\Admin\PostCrudController:

    public function configureFields(string $pageName): iterable
    {
        return [
            // ...
            ChoiceField::new('author')->setChoices(fn() => $this->getAuthorChoices()),
        ];
    }

    private function getAuthorChoices(): array
    {
        $choices = [];
        foreach($this->authorRepository->findAll() as $i => $author) {
            $choices[$author->getFullName()] = $author->getId();
        }
        return $choices;
    }

Solution

  • Actually the solution was very easy: using the AssociationField type instead of ChoiceField. The ChoiceField type is only used for passing arrays manually. To list entities, the AssociationField is definitly the one and does everything automatically. This was not precised in the documentation as the fields reference is not written yet.