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.


Comments
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.