EasyAdminBundle
EasyAdminBundle copied to clipboard
Native support of EnumField
Hi. It'd be nice if we can use EnumField natively as a choice type.
Yes, we can use enums as a choice field something like this:
// FooEnum.php
enum Foo: int
{
case BAR = 0;
}
// FooCrudController.php
IntegerField::new('foo') // too annoying to change field type according to enum's backing type
->setFormType(EnumType::class)
->setFormTypeOptions(['class' => FooEnum::class])
->formatValue(fn(Foo $v) => $v->name),
But it looks too annoying when repeated many times and we lost some features from ChoiceType like cool autocomplete widget.
Is it time to implement EnumField natively?
@javiereguiluz what do you think about this feature?
Yes, we need to improve enum support ASAP.
Just wondering. Instead of creating a new EnumField, could we improve ChoiceField to allow passing a PHP Enum to setChoices()?
Would that be enough? What else do we need? Thanks!
@javiereguiluz I think it would be clearer to have 2 distinct Fields for Choice and Enum. That would also mirror the way Symfony Form handles this.
We would need the EnumField to have a method setEnum
and the formatting to be handled automatically with the (translated?) name of the BackedEnum.
Here's my deliberately naive approach. It is basically a copy of the ChoiceField, without OPTION_CHOICES
and OPTION_USE_TRANSLATABLE_CHOICES
but with an extra OPTION_ENUM_CLASS
: https://gist.github.com/quentint/a6959da196bfcb1fd18ba8b075ed96fa
Even though I agree with @wizacedric that sticking to how Symfony handles this seems like the way to go, it is so similar to the Choice Field
and Configuration
that it could be a bad idea in this case. Or could the Choice
classes not be final, and extended for the Enum needs?
A few notes:
- My
Configuration
doesn't support the "multiple choices" setting - An
EnumFilter
could also be useful - I didn't find a way to allow explicitly translatable enum cases, so I just dumped this option. Maybe someone has an idea here 😉
Thanks @quentint the gist works as I'd expect it to.
To answer @javiereguiluz's question above:
Instead of creating a new EnumField, could we improve ChoiceField to allow passing a PHP Enum to setChoices()?
This works fine for displaying an enum, but not for editing one. When trying to edit an enum which is defined with ChoiceField
I get this error:
Object of class App\Enum\ExpertTag could not be converted to string
This is reported here: https://github.com/EasyCorp/EasyAdminBundle/issues/5641
Therefore, I'd recommend a PR which adds EnumField
as a new field option, as I agree that the underlying Symfony form type should be \Symfony\Component\Form\Extension\Core\Type\EnumType
and not \Symfony\Component\Form\Extension\Core\Type\ChoiceType
.
Closing as fixed in #6163.