PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, May 12, 2022

[FIXED] How to list entities in a ChoiceField with EasyAdmin?

 May 12, 2022     easyadmin, easyadmin3, php, symfony, symfony5     No comments   

Issue

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.



Answered By - Edouard
Answer Checked By - Cary Denson (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing