nehalist
nehalist

Reputation: 1496

Tree structure in Symfony's Entity Type

My table looks like this

categories:
- id
- name
- parent

In my form you can select multiple categories. I'm using this code for the form builder

->add('categories', EntityType::class, [
            'class' => 'AppBundle:CourseCategory',
            'choice_label' => function(CourseCategory $category) {
                return \AppBundle\Helper::categoryIndent($category) . ' ' . $category->getName();
            },
            'multiple' => true,
            'expanded' => true,
            'query_builder' => function(EntityRepository $er) {
                return $er
                        ->createQueryBuilder('u')
                        ->orderBy('u.parent');
            },
            'choice_attr' => function($category, $key, $index) {
                $attrs = [];

                $attrs['data-id'] = $category->getId();
                $attrs['class']   = 'tree-item';

                if($category->getParent() != null) {
                    $attrs['data-parent'] = $category->getParent()->getId();
                }

                return $attrs;
            }
        ])

This doesn't work so far, since the orderBy statement is wrong...

How to get a recursive tree structure here?

Edit

What I'm trying to achieve looks like this:

Category
    Subcategory 1
    Subcategory 2
        Sub-subcategory 1
    Subcategory 3
Category
    Subcategory

I do not know the depth of trees.

Upvotes: 4

Views: 2619

Answers (1)

Arkadiusz Galler
Arkadiusz Galler

Reputation: 315

I know the question is old, but maybe someone can still profit from my answer.

When displaying tree, you have to order it by "left", below my example:

->add('parent', EntityType::class,
                    array(
                        'class'         => Menu::class,
                        'choice_label' => function(Menu $menu) {
                            return TreeHelper::getIndentForTreeElement($menu) . ' ' . $menu->getTitle();
                        },
                        'query_builder' => function(EntityRepository $em) {
                            return $em->createQueryBuilder('t')->orderBy('t.lft', 'ASC');
                        }
                    )
                )

Depth of the tree or parent ids don't matter as long as tree is properly built with right and left values.

Upvotes: 2

Related Questions