New in Symfony 3.2: Lazy loading of form choices

Warning: This post is about an unsupported Symfony version. Some of this information may be out of date. Read the most recent Symfony Docs.
Contributed by
Jules Pietri
in #18332.
ChoiceType is the most powerful Symfony form type and it's used to create select drop-downs, radio buttons and checkboxes. In Symfony 3.2 we added a new feature to improve its performance: lazy loading the choice values.
First, define the choice_loader
option for the ChoiceType
and then,
use the new CallbackChoiceLoader
class to set the PHP callable executed to
get the list of choices:
1 2 3 4 5 6 7 8
use Symfony\Component\Form\ChoiceList\Loader\CallbackChoiceLoader;
use Symfony\Component\Form\Extension\Core\Type\ChoiceType;
$builder->add('constants', ChoiceType::class, [
'choice_loader' => new CallbackChoiceLoader(function() {
return StaticClass::getConstants();
},
]);
The CallbackChoiceLoader
class implements ChoiceLoaderInterface
, which
is now also implemented in every ChoiceType
subtype, such as CountryType
,
CurrencyType
, LanguageType
, LocaleType
and TimezoneType
.
Help the Symfony project!
As with any Open-Source project, contributing code or documentation is the most common way to help, but we also have a wide range of sponsoring opportunities.
Comments
Comments are closed.
To ensure that comments stay relevant, they are closed for old posts.
What this class do?
when it does it?
Its lazy mean here that will be allowed to fetch items from client side as AJAX request?
Just a few of the question that popups.
- why it's faster ?
- what we can achieve with that new CallbackChoiceLoader that we couldn't do before ?
Actually the real performance improvements have been done in 3.1, but we didn't have any news for that (see https://github.com/symfony/symfony/pull/18359).
Now this "CallbackChoiceLoader" isn't that amazing: building your choices lazily means that if no data are pre set or submitted to the choice field (new instance or nullable) and if the view is not created (often on API post routes), choices are not loaded.
If one wants to have full control of what data is loaded on pre set or submit (like the DoctrineChoiceLoader with ids), he should implement the ChoiceLoaderInterface, as said in the news it has been done for intl choice types.