Via G. Falcone 5, Pollenza (MC), Italy
+39 0733 203595

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!

Related Posts

2 comments

$choices = []; in line 29 is not used?

Yes, it’s a typo: I’m gonna fix it.

Thank you for spotting this.

Leave a reply