New in Symfony 3.2: Lazy loading of form choices

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

Can this be used to simplify the legendary problem of linked choicelists ?
This looks really amazing if it is what we all where expecting, but i cant say right now since the article say so little on the new CallbackChoiceLoader.

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.
true, we lack of context and example on why it's amazing.
- why it's faster ?
- what we can achieve with that new CallbackChoiceLoader that we couldn't do before ?
Missing the doc for now, but here's what I can say right now:

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.
anyway, if we want too validate the data we need to load the list anyway even API post or not, imho

Comments are closed.

To ensure that comments stay relevant, they are closed for old posts.