Symfony 细枝-为什么我不能访问我设置的变量?
出于某种原因,我在一个表单模板组中设置的变量在子表单块中不可用 我有一个“实体”字段类型来显示复选框的选择,以允许用户选择相关项目Symfony 细枝-为什么我不能访问我设置的变量?,symfony,variables,twig,Symfony,Variables,Twig,出于某种原因,我在一个表单模板组中设置的变量在子表单块中不可用 我有一个“实体”字段类型来显示复选框的选择,以允许用户选择相关项目 $builder ->add( 'title' ) ->add( 'apps', 'entity', [ 'class' => 'OurAdminBundle:App', 'choices' => $apps,
$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\u小部件块中的变量。请提供帮助。这是由于Symfony在调用form_小部件或任何其他form*函数系列时呈现表单字段的方式造成的 Symfony创建一个新的单独作用域,该作用域不共享父对象的作用域,以防止在渲染字段时影响作用域 如果要将变量传递给复选框小部件,请在扩展的选项小部件中编辑表单小部件调用,以传递自定义小部件复选框,因此仅为清晰起见添加了选项卡:
{{ 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
}) }}
谢谢你的建议。非常有帮助:o