简体   繁体   English

Symfony 表单主题块覆盖中不存在变量

[英]Variable does not exist within Symfony Form Theme block override

I am building a form which contains a series of categories used to search some content, defined as a ChoiceType within my Symfony FormType.我正在构建一个表单,其中包含一系列用于搜索某些内容的类别,在我的 Symfony FormType 中定义为 ChoiceType。

I pass the category list along with some other data (per-category count) (defined as the variable "aggs" in my controller) into a Twig template and create a form theme, overriding the choice_widget_options block for my categories drop-down so that I can display the extra data at render time, thus:我将类别列表与其他一些数据(按类别计数)(在我的控制器中定义为变量“aggs”)一起传递到 Twig 模板中并创建一个表单主题,覆盖我的类别下拉列表的choice_widget_options 块,以便我可以在渲染时显示额外的数据,因此:

{% form_theme form.categories _self %}
{% block choice_widget_options %}
    {% if choices is defined %}
        {% for choice in choices %}
            <option value="{{ choice.value }}">{{ choice.label }} {{ aggs }}</option>
        {% endfor %}
    {% endif %}
{% endblock choice_widget_options %}

Why is it that my block here cannot access the top-level variables defined in my controller?为什么我这里的block不能访问我的controller中定义的顶级变量? It can see the "app" global variable, but not the controller-defined ones.它可以看到“app”全局变量,但看不到控制器定义的变量。

Thanks!谢谢!

More elegant solution is to override the buildView method of AbstractType class.更优雅的解决方案是覆盖 AbstractType class 的buildView方法。

Just add:只需添加:

$view->vars[‘aggs’] = YOUR AGGS VAR;

And the use it in your form as:并以您的形式使用它:

<option value="{{ choice.value }}">{{ choice.label }} {{ form.vars.aggs }}</option>

Basically you pass the variable to your form and then you use it in twig.基本上,您将变量传递给您的表单,然后在 twig 中使用它。 The way you pass it to the form type is up to you.将其传递给表单类型的方式取决于您。 It can be a dependency injection or via the form options from the controller.它可以是依赖注入或通过 controller 中的表单选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM