2014-07-13 137 views
0

由於某種原因,我在一個表單模板塊中設置的變量在子表單塊中不可用。樹枝 - 爲什麼我無法訪問我設置的變量?

我有一個「實體」字段類型呈現一個選擇複選框允許用戶選擇相關項目...

$builder 
    ->add('title') 
    ->add(
     'apps', 
     'entity', 
     [ 
      'class' => 'OurAdminBundle:App', 
      'choices' => $apps, 
      'property' => 'title', 
      'expanded' => true, 
      'multiple' => true 
     ] 
    ) 

而這裏的呈現形式

// Effectively imported using the MopaBootstrapBundle 
// {% form_theme form 'OurAdminBundle:Form:fields.html.twig %} 

// Further in page theming 
{% form_theme form _self %} 

// Set variable when on the apps field, so it should be available to all child 
// forms 
{% block _gallery_apps_widget %} 
    {% set custom_checkboxes = 1 %} 
    {{ block('choice_widget') }} 
{% endblock %} 

// Attempt to retrieve the variable on the checkboxes within the apps entity 
/field 
{% block checkbox_widget %} 
    {{ dump(custom_checkboxes|default(0) }} // Displays 0 
{% endblock checkbox_widget %} 
模板

下面是來自fields.html.twig文件中的代碼(含有少量調試添加...

{% block choice_widget_expanded %} 
    {{ dump(custom_checkboxes|default(0)) }} 
    {% set custom_checkboxes = custom_checkboxes|default(0) %} 
    {{ dump(custom_checkboxes|default(0)) }} 
{% spaceless %} 
    {% set label_attr = label_attr|merge({'class': (label_attr.class|default(''))}) %} 
    {% set label_attr = label_attr|merge({'class': (label_attr.class ~ ' ' ~ (widget_type != '' ? (multiple ? 'checkbox' : 'radio') ~ '-' ~ widget_type : ''))}) %} 
    {% if expanded %} 
     {% set attr = attr|merge({'class': attr.class|default(horizontal_input_wrapper_class)}) %} 
    {% endif %} 
    {% for child in form %} 
     {% if widget_type != 'inline' %} 
     <div class="{{ multiple ? 'checkbox' : 'radio' }}"> 
     {% endif %} 
      <label{% for attrname, attrvalue in label_attr %} {{ attrname }}="{{ attrvalue }}"{% endfor %}> 
       {{ form_widget(child, {'horizontal_label_class': horizontal_label_class, 'horizontal_input_wrapper_class': horizontal_input_wrapper_class, 'attr': {'class': attr.widget_class|default('')}}) }} 
       {{ child.vars.label|trans({}, translation_domain) }} 
      </label> 
     {% if widget_type != 'inline' %} 
     </div> 
     {% endif %} 
    {% endfor %} 
{% endspaceless %} 
{% endblock choice_widget_expanded %} 

...兩次都成功顯示'1'。

我已經絞盡腦汁在這一個,但不能爲我的生活理解爲什麼我不能訪問checkbox_widget塊中的變量。請幫忙。

回答

1

這是由於Symfony在調用form_widget()或任何其他form*函數族時如何呈現表單字段。

Symfony創建一個新的獨立範圍,它不共享父級的範圍(爲了防止範圍污染而渲染字段)。

如果其中一個變量傳遞給複選框控件,請編輯choice_widget_expandedform_widget呼叫轉嫁custom_checkboxes爲左右(按Tab鍵添加只是爲了清楚):

{{ form_widget(child, { 
    'horizontal_label_class': horizontal_label_class, 
    'horizontal_input_wrapper_class': horizontal_input_wrapper_class, 
    'attr': {'class': attr.widget_class|default('')}, 
    'custom_checkboxes': custom_checkboxes 
}) }} 
+0

謝謝你的建議。非常有幫助:o) – TobyG

相關問題