BrocolliRob
BrocolliRob

Reputation: 23

How to format/control output of Symfony ChoiceType

Is it possible to iterate over ChoiceType values in Symfony 3? I can setup the values fine, but they just output in big block for which i can't control. I would like to loop over each value and format it/put in table/div/columns etc.

$builder->add('tOptions', ChoiceType::class, array(
    'choices'  => array(
        'one' => true,
        'two' => true,
        'three' => true,
        'four' => true,
        'five' => true,
    ),
    'expanded' => true,
    'multiple' => true,
    'required' => false,
));

Note: I am not outputting in twig, just in PHP.

echo $view['form']->widget($form['tOptions']);

Results in:

<div id="t_options_tOptions">
<input type="checkbox" id="t_options_tOptions_0" name="t_options[tOptions][]" value="0">
<label for="t_options_tOptions_0">one</label>

<input type="checkbox" id="t_options_tOptions_1" name="t_options[tOptions][]" value="1">
<label for="t_options_tOptions_1">two</label>

<input type="checkbox" id="t_options_tOptions_2" name="t_options[tOptions][]" value="2">
<label for="t_options_tOptions_2">three</label>

<input type="checkbox" id="t_options_tOptions_3" name="t_options[tOptions][]" value="3">
<label for="t_options_tOptions_3">four</label>

<input type="checkbox" id="t_options_tOptions_4" name="t_options[tOptions][]" value="4">
<label for="t_options_tOptions_4">five</label>
</div>

How does one iterate over these input options, in order to wrap each in div or split into two even columns etc.

Upvotes: 1

Views: 1305

Answers (2)

Yecodeo
Yecodeo

Reputation: 371

here my solution i used in my own project

{{form_label(form.transport)}}

 {% for key, item in form.transport.children %}
    <div class="custom-radio">
        <label for="{{item.vars.id}}">{{item.vars.label}}</label>
        <input 
            type="radio" 
            value="{{item.vars.value}}" 
            id="{{item.vars.id}}" 
            name="{{item.vars.full_name}}" 
           {{ item.vars.checked ? 'checked' : '' }} 
       >
  </div>
{% endfor %}

or you can use a form theming

{% form_theme form _self %}

{%- block choice_widget_expanded -%}
    {%- for child in form %}
        <div class="custom-radio">
            {{- form_label(child) -}}
            {{- form_widget(child) -}}
        </div>
    {% endfor -%}
{%- endblock choice_widget_expanded -%}

{{form_widget(form)}}

Upvotes: 3

lsouza
lsouza

Reputation: 2488

To customize that you'd have to create a custom template for the choices widget. Specifically, you could extend the choice_widget_options.html.php file.

To apply the styling you can follow the Form Theming in PHP documentation. It's worth noting that extending the template with Twig would be simpler.

Upvotes: 0

Related Questions