3

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?

2 Answers 2

9

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!
Sign up to request clarification or add additional context in comments.

Comments

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 %}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.