按标题Gedmo Tree Symfony排序树

时间:2016-02-21 14:21:27

标签: php symfony doctrine-orm tree

我想按名称显示我的类别树。我有一个CategoryType来创建新的Category实体,并为其分配一个带有选择框的父类别。这是我的表单类型:

/**
 * @param FormBuilderInterface $builder
 * @param array $options
 */
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('name', TextType::class, array("required" => false));
    $builder->add('parent', EntityType::class, array(
        'class' => 'CAPShopAdminBundle:Category',
        'choice_label' => 'selectBoxName',
        'placeholder' => '-- Aucune --',
        'required' => false,
        'query_builder' => function(NestedTreeRepository $r) {
            return $r->createQueryBuilder('c')
                ->orderBy('c.root, c.lvl, c.name', 'ASC');
        }
    ));
    $builder->add('save', SubmitType::class);
}

结果如下:

enter image description here

我搜索这个结果:

enter image description here

没有PHP处理,只有好的SQL查询才能实现吗?

1 个答案:

答案 0 :(得分:1)

我想我找到了解决方案。我从一个唯一的根节点开始重建我的树。这个结构更好,然后,当我在树中插入一个节点时,我从Gedmo树Bundle执行reorder()函数。

    /**
 * @param Category $category
 */
public function saveCategory(Category $category)
{

    if(!$category->getId()){ //insert
        $this->objectManager->persist($category);
        $this->objectManager->flush();

        $root = $this->categoryRepository->findOneBySlug('pieces-automobile'); //The root node
        $this->categoryRepository->reorder($root, 'name', 'ASC'); //Reoder by name
    }

    $category->setSlug($category->getId().'-'.$this->miscellaneous->slugify($category->getName(),'-'));

    $this->objectManager->flush();

}

我的树很小,最多可能有30个节点。所以每次插入节点时我都可以重新登记树。但要小心,因为reorder()是一个很重要的函数,可能需要一些大树。

我得到了没有根的树:

    /**
 * @return bool
 */
public function getAllCategories(){

    $root = $this->categoryRepository->findOneBySlug('pieces-automobile');

    $htmlTree = $this->categoryRepository->childrenHierarchy(
        $root, /* starting from root nodes */
        false, /* true to take only direct children */
        array(
            'decorate' => true,
            'representationField' => 'name',
            'html' => true,
        )
    );

    return $htmlTree;
}

结果:

enter image description here