Symfony2 choice form split in twig

12,969

Solution 1

You need to add template to the form. Here's the docs: http://symfony.com/doc/current/cookbook/form/form_customization.html

Here you got multiple examples: https://github.com/phiamo/MopaBootstrapBundle/blob/master/Resources/views/Form/fields.html.twig

This field is for you:

{% block choice_widget_expanded %}
{% spaceless %}
<div {{ block('widget_container_attributes') }}>
{% for child in form %}
    <label class="{{ (multiple ? 'checkbox' : 'radio') ~ (widget_type ? ' ' ~ widget_type : '') ~ (inline is defined and inline ? ' inline' : '') }}">
        {{ form_widget(child, {'attr': {'class': attr.widget_class|default('')}}) }}
        {{ child.vars.label|trans({}, translation_domain) }}
    </label>
{% endfor %}
</div>
{% endspaceless %}
{% endblock choice_widget_expanded %}

You can do whatever you want just leave the: {{ form_widget(child, {'attr': {'class': attr.widget_class|default('')}}) }} alone :)

  1. You need to create file YourBundle/Resources/Form/fields.html.twig
  2. Paste there the code above.
  3. Add theming to the form: {% form_theme form 'AcmeDemoBundle:Form:fields.html.twig' %}
  4. And be ready to rock'n'roll!

Solution 2

Defined number of fields:

{{ form_widget(form.type.0) }}{{ form_label(form.type.0) }}
    some html stuf
{{ form_widget(form.type.1) }}{{ form_label(form.type.0) }}

A variable number of fields:

{% for i in 0..form.type|length-1 %}
    {{ form_widget(form.type[i]) }}
    {{ form_label(form.type[i]) }}
{% endfor %}

And when we have id in choice not in order:

e.g

$typeChoice = [
    "choice 1" => 2,
    "choice 2" => 5
]

{% for type in form.type %}
    {{ form_label(type) }}
    {{ form_widget(type) }}
{% endfor %}
Share:
12,969
Wolly Wombat
Author by

Wolly Wombat

Updated on June 28, 2022

Comments

  • Wolly Wombat
    Wolly Wombat almost 2 years

    OK so i have a choice form with 2 options

    $builder->add('type', 'choice', array(
        'label' => 'User type',
        'choices' => array('1' => 'Customer', '2' => 'Supplier'),
        'expanded' => true,
        'multiple' => false,
        'required' => false,
    ));
    

    And i want to split options in view using twig to get something like this:

    {{ form_widget(form.type/choice_1/) }}
    some html stuf
    {{ form_widget(form.type/choice_2/) }}
    

    Any sugestions?