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


How to return a localized property of an entity in Symfony 2

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

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

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

{{ categories.nameFr }} and {{ categories.nameEn }}

所以我做了一个叫getName()的方法,这样我就可以使用{{ categories.name }}

我只需要访问区域设置,所以我用setter和getter向实体添加了protected $locale属性,并在调用视图之前设置了区域设置(顺便说一句,我使用@Template作为返回):

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

这是可行的,但现在我实现了一个分页捆绑包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
);

此操作失败,并显示错误消息:FatalErrorException: Error: Call to undefined method Doctrine'ORM'QueryBuilder::setLocale()

如果我在$categoriesPagination上尝试方法setLocale(),它将失败,并显示错误消息:FatalErrorException: Error: Call to undefined method Knp'Bundle'PaginatorBundle'Pagination'SlidingPagination::setLocale()

是否有方法将区域设置传递给实体?或者有更好的方法来处理这种情况吗?

谢谢,

一般情况下,您不应该执行类似propertyEnpropertyFr的操作。

只需将您的翻译与区域设置属性存储在一起,即可轻松地在查询中从数据库中获取翻译:

// 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)

但这一切以前都做过。。。

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

或者我的提示,如果使用具有KnpLabs''DoctrineBehaviors''Translatable特性的PHP 5.4+。

为了将这些与您的表单很好地集成,请使用a2lix''TranslationFormBundle。

关于使用DoctrineBehaviors''Translatable和当前区域设置代理的快速见解,请参阅此处的答案,我发现这是一个非常舒适的解决方案。

只需创建类EntityEntityTranslation,包括代理行。。。呼叫$entity->getProperty()

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