我有两个实体:供应商和类别加入了ManyToMany。
接下来,我有一个表单构建器类,我在其中添加EntityType::class
。
类别结构:
id, categoryName, parentId - where parentIds value can be:
0 - head category
1 - subcategory
etc
我需要在结构中显示(在树枝模板中)类别:
Category1
Subcategory1
Subcategory2
Category2
Subcategory3
Subcategory4
等。其中Category是某种标题和子类别是复选框。
请有人给我一个提示如何做到这一点。
答案 0 :(得分:0)
基于我们在评论中讨论的内容,以下内容适用于我的测试环境:
<强>在SupplierType::buildForm
强>:
->add('categories', EntityType::class, [
'class' => Category::class,
'choice_label' => 'name',
'group_by' => 'parent',
'multiple' => true,
'expanded' => true
])
虽然没有表单自定义,但这只会呈现没有标题的复选框。这将在此处讨论:https://github.com/symfony/symfony/issues/5489#issuecomment-194943922
通过MaxE17677实施修补程序会看起来像这样 :
{% extends 'base.html.twig' %}
{% form_theme form _self %}
{# @see: https://github.com/symfony/symfony/issues/5489#issuecomment-194943922 #}
{%- block choice_widget_expanded -%}
<div {{ block('widget_container_attributes') }}>
{% for name, choices in form.vars.choices %}
{% if choices is iterable %}
<label class="choice_category">
<strong>
{{ choice_translation_domain is same as(false) ? name : name|trans({}, choice_translation_domain) }}
</strong>
</label>
<div>
{% for key,choice in choices %}
{{ form_widget(form[key]) }}
{{ form_label(form[key]) }}
{% endfor %}
</div>
{% else %}
{{- form_widget(form[name]) -}}
{{- form_label(form[name], null, {translation_domain: choice_translation_domain}) -}}
{% endif %}
{% endfor %}
{%- endblock choice_widget_expanded -%}
{% block body %}
<div class="container">
{{ form_start(form) }}
{{ form_row(form.categories) }}
{{ form_end(form) }}
</div>
{% endblock %}
预览强>:
关键是您使用ChoiceType
的{{3}}功能。要使其与当前实体一起使用,您可能还需要使用EntityType
// ...
'query_builder' => function (EntityRepository $er) {
return $er
->createQueryBuilder('c')
->where('c.parentId = 1')
;
},
设置。类似的东西:
// ...
'group_by' => function ($category) {
// *pseudo-code*
return $category->getParent()->getName();
}
以及:
{{1}}