How to render each items of ChoiceType to add to them div and classes as I need

时间:2017-08-04 13:10:44

标签: symfony

In past I render a form, but now I render each element of form in template.

How to render each items of ChoiceType to add to them div and classes as I need.

I need to group all options in pairs wit two in one div <div class="col-xs-2"> <label class="checkbox"><input type="checkbox" class="styler" checked=""> 1</label> <label class="checkbox"><input type="checkbox" class="styler"> 2</label> </div> and also and also for all options.

I need to transform the Symfony 3 code (form elemetn of type ChoiceType) from :

<div class="col-xs-12">
  <div class="form-group">
    <label class="col-xs-2 text-right control-label">{% trans %}Example{% endtrans %}</label>
    <div class="col-xs-2">
      <label class="checkbox">{{ form_widget(form.examples, {'attr': {'class': 'form-control styler', 'checked': ''}}) }} Example</label>
    </div>
  </div>
</div>

To that form:

<div class="col-xs-12">
  <div class="form-group">
    <label class="col-xs-2 text-right control-label">{% trans %}Example{% endtrans %}</label>
    <div class="col-xs-2">
      <label class="checkbox"><input type="checkbox" class="styler" checked=""> 1</label>        
      <label class="checkbox"><input type="checkbox" class="styler"> 2</label>        
    </div>
    <div class="col-xs-3">
      <label class="checkbox"><input type="checkbox" class="styler"> 3</label> 
      <label class="checkbox"><input type="checkbox" class="styler" checked=""> 4</label>       
    </div>
    <div class="col-xs-3">
      <label class="checkbox"><input type="checkbox" class="styler" checked=""> 5</label> 
      <label class="checkbox"><input type="checkbox" class="styler"> 6</label>       
    </div>
  </div>
</div>

I am new in Symfony. Thank you for help.

1 个答案:

答案 0 :(得分:1)

假设你有这种形式:

class MyFormType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('inputName', ChoiceType::class, array(
            'label' => 'Choice',
            'choices' => [
                'Choice 1'=>'c1',
                'Choice 2'=>'c2',
                'Choice 3'=>'c3',
                'Choice 4'=>'c4',
                'Choice 5'=>'c5',
                'Choice 6'=>'c6',
            ]
        ));
    }

    public function getName()
    {
        return 'my_form';
    }

}

然后您可以从表单中访问和分组选项,如下所示:

{{ form_widget(form) }}

{% set groupSize = 2 %}
{% set auxGroup = 0 %}
<div>
    {% for choice in form.inputName.vars.choices %}
        {{ dump(choice) }}
        {% set auxGroup = auxGroup + 1 %}
        {% if auxGroup == groupSize %}
            </div><div>
            {% set auxGroup = 0 %}
        {% endif %}
    {% endfor %}
</div>

我没有添加类,标签和其他前端内容,因为它不相关。

希望它有所帮助!