2016-12-01 56 views
0

我創建了一個名爲'AgenceSelectType'的自定義表單字段,它基本上是一個具有默認值和自定義主題的EntityType。Symfony自定義字段模板標籤呈現兩次

每當我用這種類型渲染一個表單時,標籤會被渲染兩次。這讓我發瘋。我錯過了什麼?

的Symfony 3.1在Ubuntu 16.04 PHP 7.1

我fields.html.twig文件:

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

我的自定義類型

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

預先感謝您對此類緩解我一個瘋狂的:-)

回答

2

你如何顯示在你的視圖中的表格行?

如果您使用form_row(form.agence),這是正常的行爲,因爲你block agence_select_widget包括標記,並{{ form_row() }}form_label + form_widget一個shortend。 我認爲你的agence_select_widget塊應該只包含輸入視圖,而不是標籤視圖。

如果你一定要你agence_select_widget包括標籤,然後使用{{form_widget(form.agence) }}顯示標籤和輸入,不使用{{form_row() }}(但如果你這樣做,你不這樣做是正確的方式)。

對於一個很好用的小部件和標籤塊的,我會探微移動

<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> 
{% block agence_select_widget %}

到一個新{% block agence_select_label %}

+0

你讓我一天的感謝!即使第一個選項更清潔,我也會選擇第二個選項,因爲根據底層數據,該字段也可以是隱藏類型。 –