我有一个包含
的“类别”实体/**
* @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()
。
如果我尝试使用setLocale()
上的$categoriesPagination
方法,则会失败并显示错误消息:FatalErrorException: Error: Call to undefined method Knp\Bundle\PaginatorBundle\Pagination\SlidingPagination::setLocale()
有没有办法将语言环境传递给实体?或者是否有更好的方法来处理这种情况?
谢谢,
答案 0 :(得分:5)
一般情况下,您不应该执行propertyEn
和propertyFr
之类的操作。
只需将您的翻译与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)
但这一切都已经完成......
您应该使用Gemo\DoctrineExtensions\Translatable,可以使用Stof\DoctrineExtensionsBundle轻松与symfony2集成
...或者我的提示,如果使用PHP 5.4+和可用的特征KnpLabs\DoctrineBehaviors\Translatable。
为了将这些与表单很好地集成,请使用a2lix\TranslationFormBundle。
有关使用DoctrineBehaviors \ Translatable和当前语言环境代理的快速见解,请参阅my answer here,我发现这是一个非常舒适的解决方案。
只需创建课程Entity
和EntityTranslation
,包含代理行... call $entity->getProperty()
- >当前区域设置自动应用。尽可能简单: - )