Reputation: 403
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.
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;
}
Upvotes: 1
Views: 4872
Reputation: 1700
There are two cases:
Example:
AssociationField::new('users', 'Users');
Example:
ChoiceField::new('users', 'Users')
->setChoices($userChoices) //$usersChoices is the array of pair label/identifier ['label' => 'identifier']
->allowMultipleChoices() // If you need multiple Choices
That's it.
Upvotes: 0
Reputation: 1
As you do in EasyAdmin 4.0, when, for example, you do not have an association field, you should not even save said field in the database but you only use that field to filter another associated field (that is a association field).
Example:
You have 3 tables
State(id,description,code)
county(id, description, state_id)
Person(id,name,county_id)
If we notice in the Person
table we do not have the id of the State
table because with the County
table we already have the state_id
and through the county_id
field, we can access it and recover the state_id
, now as I create a field to filter the County
by State
combo.
They are two dependent combos, I must select the State
first so that in another combo it shows me the County only of that selected State
, I speak in a CRUD of EasyAdmin 4.
Upvotes: 0
Reputation: 403
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.
Upvotes: 2