Twig Question

Symfony Custom Field Template label is rendered twice

I created a custom form field called 'AgenceSelectType' which is basically an EntityType with Defaults values and a custom theme.

Every time I render a form with this Type the label gets rendered twice. This is driving me mad. What am I missing ?

Symfony 3.1 on Ubuntu 16.04 php 7.1

My fields.html.twig file :

{% block agence_select_widget %}
{% spaceless %}
<div class="col-xs-12 col-sm-3 col-md-3 col-lg-3">
<label{% for attrname,attrvalue in attr %} {{attrname}}="{{attrvalue}}"{% endfor %}>
{{label }}
</label>
</div>
<div class="col-md-9 col-sm-9 col-xs-12 form-group">
<select {{ block('widget_attributes') }} class="form-control" >
{%- if preferred_choices|length > 0 -%}
{% set options = preferred_choices %}
{{- block('choice_widget_options') -}}
{%- if choices|length > 0 and separator is not none -%}
<li disabled="disabled">{{ separator }}</li>
{%- endif -%}
{%- endif -%}
{%- set options = choices -%}
{{- block('choice_widget_options') -}}
</select>
</div>
{% endspaceless %}
{% endblock %}

{%- block choice_widget_options -%}
{% for group_label, choice in options %}
{%- if choice is iterable -%}
<optgroup label="{{ group_label|trans({}, translation_domain) }}">
{% set options = choice %}
{{- block('choice_widget_options') -}}
</optgroup>
{%- else -%}
<option value="{{ choice.value }}"{% if choice is selectedchoice(value) %} selected="selected"{% endif %}>{{ choice.label }}</option>
{%- endif -%}
{% endfor %}
{%- endblock choice_widget_options -%}


And my custom type

class AgenceSelectType extends AbstractType
{
public function configureOptions(OptionsResolver $resolver)
{
$resolver->setDefaults(array(
'class' => 'AppBundle:Agence',
'label' => 'Agence',
'choice_label' => function ($agence) {
return $agence->getNom();
},
'required' => true,
));
}

public function getParent()
{
return EntityType::class;
}
}


Thank you in advance for relieving me from such a madness :-)

VaN VaN
Answer

How are you displaying the form row in your view ?

If you're using form_row(form.agence), it's normal behavior, because your block agence_select_widget includes the label, and {{ form_row() }} is a shortend for form_label + form_widget. I think your agence_select_widget block should only contains the input view, not the label view.

If you definitely wants your agence_select_widget to include the label, then use {{form_widget(form.agence) }} to display both label and input, dont use {{form_row() }} (but if you do this, you're not doing it the right way).

For a good use of widget and label block, i would juste move

<div class="col-xs-12 col-sm-3 col-md-3 col-lg-3">
    <label{% for attrname,attrvalue in attr %} {{attrname}}="{{attrvalue}}"{% endfor %}>
      {{label }} 
    </label> 
</div>

from your {% block agence_select_widget %} to a new {% block agence_select_label %} block

Comments