如何在下拉列表ObjectSelect中实现一组元素

时间:2016-10-10 10:30:45

标签: php select doctrine-orm zend-framework2 zend-form

如何在下拉列表ObjectSelect' optgroup_identifier'

中实施一组元素

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' => [
            ],
        ],
    ],
]);

类别表格相关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;

组名必须是父类 $category->getParent()->getName()

1 个答案:

答案 0 :(得分:0)

值得庆幸的是,Doctrine没有对分组进行任何查询;它在内部完成。 optgroup_identifier只是用于获取组名的getter的名称,因此getter可以返回您想要的任何内容。

Entity\Category中,添加专用于返回类别父名称的方法。确保它与任何字段不一致,因此Doctrine不会将整个对象代理返回到表单中。例如:

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

由于根类别没有父级,$this->parent将为null。请注意这种情况,以避免脚本崩溃并返回空字符串作为它的名称。

然后,将此getter名称放在表单的optgroup_identifier中。最终结果将与样本数据的屏幕截图相同。enter image description here