Symfony Gedmo树与可翻译的听众

时间:2012-12-14 12:12:01

标签: php symfony tree translation

我在Symfony2项目中使用Gedmo Tree。

$em = $this->getDoctrine()->getEntityManager();

$options = array(
    'decorate' => true,
    'rootOpen' => '<ul>',
    'rootClose' => '</ul>',
    'childOpen' => '<li>',
    'childClose' => '</li>',
    'nodeDecorator' => function($node) {
        return '<a class="menu" href="#">'.$node['name'].'</a>';
    }
);


$category = $em->getRepository('MyMainBundle:Category')->childrenHierarchy(
    null, /* starting from root nodes */
    false, /* load all children, not only direct */
    $options
);

print_R($category);

它有效,但问题是字段名称是可翻译的。在类别表中,它是NULL,值保存在category_translations表中,但我的代码只返回类别表中的字段。

尝试添加列表:

$evm = new \Doctrine\Common\EventManager();

$translatableListener = new \Gedmo\Translatable\TranslatableListener();
$translatableListener->setTranslatableLocale('en');
$evm->addEventSubscriber($translatableListener);

并改变:

$em = $this->getDoctrine()->getEntityManager();

使用:

$em = $this->getDoctrine()->getEntityManager(null,null,$evm);

但没有帮助。

了解query hint,但没有查询可以使用它。

1 个答案:

答案 0 :(得分:1)

这应该有效: 创建自定义NestedTreeRepository 并覆盖 getNodesHierarchyQuery 方法,以便在返回的查询上调用 setHint

namespace My\Bundle\Entity;

use Doctrine\ORM\EntityRepository;
use Gedmo\Tree\Entity\Repository\NestedTreeRepository;

/**
 * CategoryRepository
 */
class CategoryRepository extends NestedTreeRepository
{
    /**
     * {@inheritDoc}
     */
    public function getNodesHierarchyQuery($node = null, $direct = false, array $options = array(), $includeNode = false)
    {
        $query = $this->getNodesHierarchyQueryBuilder($node, $direct, $options, $includeNode)->getQuery();
        $query->setHint(
            \Doctrine\ORM\Query::HINT_CUSTOM_OUTPUT_WALKER,
            'Gedmo\\Translatable\\Query\\TreeWalker\\TranslationWalker'
        );
        return $query;
    }
}

不要忘记将您的存储库分配给您的实体:

namespace My\Bundle\Entity;

use Doctrine\ORM\Mapping as ORM;
use Gedmo\Mapping\Annotation as Gedmo;

/**
 * Category
 *
 * @Gedmo\Tree(type="nested")
 * @ORM\Table()
 * @ORM\Entity(repositoryClass="CategoryRepository")
 */
class Category
{
}