fbpx

Symfony form pills – form type options

Today we are going to tackle a problem that I’ve recently faced with Symfony form types.

Scenario: I need a choice type of a certain entity (Foo) with values that follows a certain logic

I’ve built up a FooChoiceType because I don’t want to inject fooAdapter in each form where I’m going to use FooChoiceType.

All worked like a charm but after a while I noticed that getFoos should accept a parameter (array) in order to filter Foo objects by, for instance, an attribute (for this example, type). Let’s say I need FooChoices of type x and y in a FormType and FooChoices of type z in another FormType: it is pretty easy to understand that types should be passed as an option to FooChoices from FormType that use it.

Question: How can I pass to getFoos an option directly into configureOptions?

Answer

Use OptionResolver normalizer

How does this work?

By creating a closure

we are delaying choices evaluation in order to populate it only when types is available; if no types is passed from FormType(s) we have a fallback ([]) value.

That’s it; super easy!

DonCallisto
DonCallisto
Articoli: 21

2 commenti

Lascia una risposta

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *

Questo sito usa Akismet per ridurre lo spam. Scopri come i tuoi dati vengono elaborati.