The EntityType field defined by Symfony Forms allows you to represent all the values
stored for some Doctrine Entity via a <select>
HTML element or a collection of
radio buttons or checkboxes. It extends the ChoiceType field, one of the most
versatile (and complex) types in Symfony Forms.
The biggest drawback of EntityType
is that it can cause performance issues
when rendering an entity with many values. The common solution is to create an
autocomplete field using a combination of PHP and JavaScript code.
In Symfony 7.2 we're simplifying this with the introduction of a LazyChoiceLoader
that implements an on-demand choice loading strategy. You can use it in your form
types via the choice_lazy
option:
1 2 3 4
$formBuilder->add('user', EntityType::class, [
'class' => User::class,
'choice_lazy' => true,
]);
Internally, this loader keeps the choice list empty until the values are needed (avoiding unnecessary database queries). When form values are provided or submitted, it retrieves and caches only the necessary choices.
The front-end part needed to display the choices dynamically to the user is still not provided. To achieve this, you can use the autocomplete field from Symfony UX.
Great work !
This is great. I think it also saves you a lot of hassle when using conditional choices.