2012-07-06 39 views
4

我試圖自定義Symfony2表單渲染,以便爲生成的每個選擇添加一個類。 我認爲有一個自定義form_div_layout.html.twig:Symfony2:爲每個選擇添加類

{% block choice_widget_collapsed %} 
{% spaceless %} 
    <select class='myclass' {{ block('widget_attributes') }}{% if multiple %} multiple="multiple"{% endif %}> 
    {% if empty_value is not none %} 
     <option value="">{{ empty_value|trans({}, translation_domain) }}</option> 
    {% endif %} 
    {% if preferred_choices|length > 0 %} 
     {% set options = preferred_choices %} 
     {{ block('choice_widget_options') }} 
     {% if choices|length > 0 and separator is not none %} 
      <option disabled="disabled">{{ separator }}</option> 
     {% endif %} 
    {% endif %} 
    {% set options = choices %} 
    {{ block('choice_widget_options') }} 
</select> 
{% endspaceless %} 
{% endblock choice_widget_collapsed %} 

,並使用它與

{% form_theme form 'YOPYourOwnPoetBundle:Form:form_div_layout.html.twig' %} 

會做的伎倆。

但是,'myclass'類不會添加到select中。 我在做什麼錯?

+0

你是否偶然通過了其他課程?如果你也在這裏粘貼生成的html,這將有所幫助。 – gilden 2012-07-06 06:21:31

回答

4

您應該首先確保您嘗試使用的主題文件與您在form_theme表達式中使用的名稱相同,並且文件確實存在。我不記得Twig是否拋出異常,以防這些不匹配。

此外,在構建表單或呈現表單時,您可能會意外傳遞class屬性。會發生什麼是您的元素現在有兩個class屬性。

解決方法是將您的新類實際添加到現有類的集合中。

{% block choice_widget_collapsed %} 
{% spaceless %} 
{% set label_attr = label_attr|merge({class: label_attr.class|default('') ~ ' required'}) %} 
    {% set attr = attr|merge({class: (attr.class|default('') ~ ' myclass')|trim}) %} 
    <select {{ block('widget_attributes') }}{% if multiple %} multiple="multiple"{% endif %}> 
    {# ... #} 
</select> 
{% endspaceless %} 
{% endblock choice_widget_collapsed %} 

這允許您添加任何可選的類,您可能需要爲特定元素稍後。

編輯

望着Sf2的Github上repsitory似乎主題文件最近已更改。在版本2.0中*,您應該在版本2.1中覆蓋choice_widget *正確的塊是choice_widget_collapsed

+0

你說得對!我正在使用Symfony2.0.14,所以我正在查看文件form_div_layout.html.twig的錯誤版本。將一個class ='myclass'添加到choice_widget而不是choice_widget_collapsed中。此外,你的解決方案使用{%set attr = attr | merge({class:'myclass'〜(attr.class is defined?''〜attr.class:'')})%}也可以,米將會使用。非常感謝。 – 2012-07-06 07:02:56

+0

+1爲合併屬性,整潔的解決方案! – 2012-07-06 09:33:18

0

,我想你應該或者表格的主題行更改爲:

{% form_theme form 'YOPYourOwnPoetBundle:Form:form_div_layout.html.twig' %} 

,或者你需要改變你的樹枝文件的名稱爲fields.html.twig

兩者必須匹配。

+0

模板名稱無關緊要。 – gilden 2012-07-06 06:19:53

+0

@gilden如果您嘗試通過form_theme「加載」一個新的樹枝模板,那麼模板文件的名稱應該與您想加載的名稱不符,否則將不會有文件加載 – Timo 2012-07-06 06:23:19

+0

沒有一次有I必須命名我的表單主題模板'form_div_layout.html.twig'。即使食譜文章在[示例](http://symfony.com/doc/current/cookbook/form/form_customization.html#method-2-inside-a-separate-template)中使用了不同的模板名稱。 – gilden 2012-07-06 06:26:07

相關問題