如何使用symfony3,doctrine2和stofDoctrineExtensionsBundle

时间:2016-04-09 18:21:49

标签: doctrine-orm tree symfony doctrine-extensions stofdoctrineextensions

我正在使用Symfony v3.0.4,Doctrine v2.5.4和StofDoctrineExtensionsBundle [1]来管理树结构。

要设置树结构,我在Symfony.com上使用了文档[2],然后在GitHub上使用了文档[3]。

然后我继续进行树设置 - 使用示例[4]中的树实体,并使用[5]中的代码创建树。

我没有使用[6]和[7],因为它似乎没有必要(据我可以告诉树作品并在没有它的情况下显示)。见更新。

到目前为止,我在数据库中有一个树结构并显示它我修改了示例[8]。像这样:

<?php

namespace AppBundle\Controller;

use AppBundle\Entity\Category;
use Sensio\Bundle\FrameworkExtraBundle\Configuration\Route;
use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;

class TreeController extends Controller
{
    /**
     * @Route("/tree", name="tree")
     */
    public function treeAction(Request $request)
    {
        $em = $this->getDoctrine()->getManager();

        $repo = $em->getRepository('AppBundle:Category');
        $options = array(
            'decorate' => true,
            'rootOpen' => '<ul>',
            'rootClose' => '</ul>',
            'childOpen' => '<li>',
            'childClose' => '</li>',
            'nodeDecorator' => function($node) {
                return '<a href="/some_path/...">'. $node['title'] .'</a>';
            }
        );

        $htmlTree = $repo->childrenHierarchy(
            null, /* starting from root nodes */
            false, /* false: load all children, true: only direct */
            $options
        );

        return $this->render('tree/tree_show.html.twig', array('project_tree' => $htmlTree));
    }
}

如果我像这样修改一行:

'nodeDecorator' => function($node) {
    return '<a href="/project_path/'. implode('/', getPath($node)) .'">'. $node['title'] .'</a>';
}

为了获得树的每个元素的路径,我得到错误:

Fatal error: Call to undefined function AppBundle\Controller\getPath()
500 Internal Server Error - FatalThrowableError

如[9]中所见,NestedTreeRepositry有一个方法getPath()。

更新:我尝试了[6]但没有设置它。然后我尝试了[7]设置好了,但仍然是错误仍然一样!

请指教。 感谢您的时间和知识。

2 个答案:

答案 0 :(得分:1)

使用

中存在的功能getPath()

"vendor/gedmo/doctrine-extensions/lib/Gedmo/Tree/Entity/Repository" in the file "NestedTreeRepository.php"

"vendor/gedmo/doctrine-extensions/lib/Gedmo/Tree/Traits/Repository/ORM" in the file "NestedTreeRepositoryTrait.php"

必须像这样修改代码块:

nodeDecorator' => function($node) use ($repo)
{
    return '<a href="/project_path/'. @implode('/', $repo->getPath($repo->findOneBy(array('id' => $node['id'])))) .'">'. $node['title'] .'</a>';
}

注意添加

use ($repo)

@implode('/', $repo->getPath($repo->findOneBy(array('id' => $node['id']))))

有了这个 - 应该没有undefined function错误

答案 1 :(得分:1)

我遇到了同样的问题,因此我使用了getPathInfo(),而且效果很好。