Selectedchoice(selected_value) example


I am building a form in which a bunch of sub form elements depend on a selection made by the user.

So in my TYPE class to define the form, I have :

class MyFormType extends AbstractType
    public function buildForm(FormBuilderInterface $builder, array $options)
        $builder->add('customType', ChoiceType::class, array(
            'label'=>'custom type',
            'choices' => array(
                'choice 1' => 'choice 1',
                'choice 2' => 'choice 2',
            'multiple' => false,

        // ...

    // ...

In the doc it says there that:

It's significantly faster to use the selectedchoice(selected_value) test instead when using Twig.

I looked at selectedchoice(selected_value). The idea is to change the sub-fields that are embedded in the form depending the selection made by the user without sending a new request to the server.

It describes the use of selectedchoice(selected_value) as this:

This test will check if the current choice is equal to the selected_value or if the current choice is in the array (when selected_value is an array). 1 <option {% if choice is selectedchoice(value) %} selected="selected"{% endif %} ...>

I don't understand how to apply this example in the case that I have in my TWIG file that renders the view:

{{ form_row(MyFormType.customType) }}

How can I get the choices implied by {{ form_row(MyFormType.customType) }} and use it with that:

<option {% if choice is selectedchoice(value) %} selected="selected"{% endif %} ...>

try to set value in controller, and it will be rendered as selected choice.