2016-12-08 38 views
0

我有兩個實體:Supplier和Category加入ManyToMany。如何從實體顯示子類別?

接下來,我有一個表格生成器類,我添加了EntityType::class

分類結構:

id, categoryName, parentId - where parentIds value can be: 
0 - head category 
1 - subcategory 
etc 

我需要顯示(在樹枝模板)與結構類:

Category1 
    Subcategory1 
    Subcategory2 
Category2 
    Subcategory3 
    Subcategory4 

等,其中類別是某種報頭和子類別的複選框是。

請有人給我一個小費如何做到這一點。

+0

因此,只有子類連接到供應商? – Yoshi

+0

類別與像這樣的結構:(parentId的確定類別是頭類別或子類別) ID,類別名稱,parentId的 - 其中parentIds值可以是: 0 - 頭類別 1 - 子類別 等 – Dakotha

+0

所以應該怎麼反應那?你發佈一個問題,我試圖獲得更多的信息,你通過重複問題的相同信息來回答。幫我幫你... – Yoshi

回答

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 %} 

預覽

Preview


關鍵的是您使用ChoiceTypegroup_by功能。要使其與當前實體協同工作,您可能還需要使用query_builder設置EntityType。喜歡的東西:

// ... 
'query_builder' => function (EntityRepository $er) { 
    return $er 
     ->createQueryBuilder('c') 
     ->where('c.parentId = 1') 
    ; 
}, 

連同:

​​
+0

我打算在幾個小時內檢查一下,但我覺得它有幫助我很多。謝謝Yoshi。 – Dakotha