Tell me how you can implement the grouping of elements in the ObjectSelect ' optgroup_identifier ' drop-down list (groups by field in the Example table)

Form\CategoryForm.php

 $this->add([ 'type' => ObjectSelect::class, 'name' => 'category', 'options' => [ 'label' => 'Категория', 'object_manager' => $this->getObjectManager(), 'target_class' => Category::class, 'property' => 'name', 'optgroup_identifier' => '???', 'optgroup_default' => 'Главная', 'empty_option' => '== Категория ==', 'is_method' => true, 'find_method' => [ 'name' => 'findAllChildCategories', 'params' => [ ], ], ]); 

The category table is self-referencing

Entity\Category.php

 /** * @var \Doctrine\Common\Collections\Collection * * @ORM\OneToMany(targetEntity="Application\Entity\Category", mappedBy="parent", cascade={"remove"}) */ private $children; /** * @var \Application\Entity\Category * * @ORM\ManyToOne(targetEntity="Application\Entity\Category", inversedBy="children") * @ORM\JoinColumns({ * @ORM\JoinColumn(name="parent", referencedColumnName="id", nullable=true) * }) */ private $parent; 

Group names should be parental categories.

$category->getParent()->getName()

    1 answer 1

    Add an extra function to the Entity\Category specifically for taking a name from $this->parent . The function name should not match any other fields, so that Doctrine does not try to insert a whole proxy object into the form.

    For example:

     public function getParentName() { if(!$this->parent) return ''; return $this->parent->getName(); } 

    Paste this name into optgroup_identifier . Doctrine especially does not do anything magically, it just calls the getter under this name, which means it can be anything.

    The function itself checks for the presence of parent in case the root category. If yes, return blank text. The result is as in the picture. Is this how it should be?

    result

    • Everything works amazingly !!! Thank you very much! You are a genius)) - Drakulitka