如何在Symfony 2中返回实体的本地化属性

Oyl*_*lex 3 php orm entities symfony doctrine-orm

我有一个"类别"实体包含

/**
 * @ORM\Column(type="string", length=255)
 */
protected $nameFr;

/**
 * @ORM\Column(type="string", length=255)
 */
protected $nameEn;
Run Code Online (Sandbox Code Playgroud)

现在,我正在尝试在视图中显示本地化名称,我可以使用以下方式显示其中一个:

{{ categories.nameFr }} and {{ categories.nameEn }}
Run Code Online (Sandbox Code Playgroud)

所以我制作了一个方法,getName()所以我可以使用{{ categories.name }}

我只需要访问语言环境,所以我protected $locale使用setter和getter向实体添加了一个属性,并在调用视图之前设置了语言环境(顺便说一下,我使用@Template进行返回):

$locale = $this->getRequest()->getLocale();
$categories->setLocale($locale);

return array(
    'categories' => $categories
);
Run Code Online (Sandbox Code Playgroud)

这是有效的,但现在我实现了一个分页包KnpLabs/KnpPaginatorBundle,它需要发送一个查询而不是实体:

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

$categoriesQuery = $em->createQueryBuilder()
    ->select('category')
    ->from('OylexCategoryBundle:Category', 'category')
;

$locale = $this->getRequest()->getLocale();

$categoriesQuery->setLocale($locale);

$paginator  = $this->get('knp_paginator');
$categoriesPagination = $paginator->paginate(
    $categoriesQuery,
    $this->get('request')->query->get('page', 1),
    30
);

return array(
    'categoriesPagination' => $categoriesPagination
);
Run Code Online (Sandbox Code Playgroud)

这失败并显示错误消息:FatalErrorException: Error: Call to undefined method Doctrine\ORM\QueryBuilder::setLocale().

如果我尝试的方法setLocale()$categoriesPagination,相反,它失败,出现错误信息:FatalErrorException: Error: Call to undefined method Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination::setLocale()

有没有办法将区域设置传递给实体?还是有更好的方法来处理这种情况?

谢谢,

Nic*_*ich 5

你不应该做这样的事情propertyEnpropertyFr一般.

只需将您的翻译与locale属性一起存储,这样就可以轻松地从查询中的数据库中获取它们:

// example findByLocale($locale) method

->select('entity.property')
->from('AcmeMyBundle:Entity', 'entity')   
// or inside a repository $this->createQueryBuilder('entity')

->where('entity.locale = :locale')
->setParameter('locale', $locale)
Run Code Online (Sandbox Code Playgroud)

但这一切都已经完成......

您应该使用Gemo\DoctrineExtensions\Translatable,它可以使用Stof\DoctrineExtensionsBundle轻松地与symfony2集成

...或者我的提示,如果使用PHP 5.4+和特征可用KnpLabs\DoctrineBehaviors\Translatable.

为了将这些与表单很好地集成,请使用a2lix\TranslationFormBundle.

请参阅我的答案,以便快速了解如何使用DoctrineBehaviors\Translatable和当前的语言环境代理,我发现这是一个非常舒适的解决方案.

只需创建类,EntityEntityTranslation包括代理行...调用$entity->getProperty()

- >自动应用当前区域设置.尽可能简单:-)