kornjan
kornjan

Reputation: 15

Symfony2 twig form_widget customize html

How can I customize the the following code? I what to use checkboxes coming out of a Database.

This is my Form

$builder->add('entityname', 'entity', array(
             'class'    => 'MyBundle:applicant',
             'label'    => 'label',
             'property' => 'name',
             'expanded' => true,
             'required' => false,
             'multiple' => true,
             'attr' => array('class' => 'css-checkbox')

This is my Twig Layout

<div>
        <div>
            {% for entity in form %}
                {{ form_widget(entityname) }}
            {% endfor %}
        </div>
</div>

This is what what I see in HTML:

<div id="name" class="css-checkbox">
<input type="checkbox" id="name_1" name="name[entityname][]" value="1" />
<label for="name_1">AD DNS</label>
<input type="checkbox" id="name_2" name="name[entityname][]" value="2" />
<label for="name_2">Print</label>
<input type="checkbox" id="name_3" name="name[entityname][]" value="3" />
<label for="name_3">Citrix</label>
<div>

What I want to have is:

 <div id="name" class="css-checkbox">
<div>
        <input type="checkbox" id="name_1" name="name[entityname][]" value="1" />
    </div> 
    <div>
        <label for="name_1">AD DNS</label>
    </div> 
    <div>
       <input type="checkbox" id="name_2" name="name[entityname][]" value="2" />
    </div> 
    <div>
       <label for="name_2">Print</label>
    </div> 
 <div>
       <input type="checkbox" id="name_3" name="name[entityname][]" value="3" />
    </div> 
    <div>
       <label for="name_3">Citrix</label>
    </div>  
  <div>

How can I handle this with Twig?

Upvotes: 1

Views: 11600

Answers (2)

Pawel
Pawel

Reputation: 1692

You have two options to override form rendering: 1. override widget in the template 2. extends symfony .twig file woth the form elements definition

for more detilas see here: http://symfony.com/doc/current/cookbook/form/form_customization.html

Upvotes: 1

You could add this to your twig template:

{% form_theme form _self %}

{% block checkbox_widget %}
{% spaceless %}
<div>
    <input type="checkbox" {{ block('widget_attributes') }}{% if value is defined %} value="{{ value }}"{% endif %}{% if checked %} checked="checked"{% endif %} />
</div>
<div>
<label  for="{{ id }}">{{ label|trans }}</label>
</div>

{% endspaceless %}
{% endblock checkbox_widget %}

Upvotes: 0

Related Questions