Search code examples
symfonydoctrine-ormself-referenceformbuilder

Symfony formbuilder self-reference entity grouped


I want a choice list (dropdown) grouped by parent categories (not selectable). Is this even possible?

Example:
 - Vehiculs (not selectable)
 -- Car (selectable)
 -- Boat (selectable)
 - Computers (not selectable)

Entity Category

    /**
     * @ORM\OneToMany(targetEntity="Category", mappedBy="parent")
     **/
    private $children;

    /**
     * @ORM\ManyToOne(targetEntity="Category", inversedBy="children")
     * @ORM\JoinColumn(name="parent_id", referencedColumnName="id", nullable=true, onDelete="SET NULL")
     **/
    private $parent;

Form:

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title', 'text',
                [
                    'attr' => ['placeholder' => 'Titel', 'class' => 'form-control', 'autocomplete' => 'off'],
                    'label' => false
                ]
            )
            ...
            ->add('category', 'entity',
                [
                    'property' => 'name',
                    'class' => '***ArticleBundle:Category',
                ]
            )
        ;
    }

With the code above i only get the parents and they are selectable. I would like to group the children of those parents (1 depth) and make only the children selectable options.


Solution

  • You can not directly tell symfony to create a tree select in form builder.

    First, you have to check here; http://symfony.com/doc/current/reference/forms/types/entity.html

    You can use query builder on your entity field to get parent - child relation but parents also would be selectable.

    So you have to look another solutions like this: How to disable specific item in form choice type?