2 回答
如何使用 Knp\DoctrineBehaviors 魔法代理翻译
鉴于您有MyClass并MyClassTranslation遵循命名约定(以 Translation 为后缀的翻译类)。
只有不需要翻译的属性存在MyClass,所有可翻译的属性都存在MyClassTranslation。
假设可翻译属性应为description.
MyClass.php
注意:属性description和 getter/setter 都不是descriptionin MyClass.... 否则__call()将无法正确调用!
class MyClass
{
use \Knp\DoctrineBehaviors\Model\Translatable\Translatable;
public function __call($method, $arguments)
{
return $this->proxyCurrentLocaleTranslation($method, $arguments);
}
protected $nonTranslatableProperty;
// ...
MyClassTranslation.php
use Doctrine\ORM\Mapping as ORM;
class MyClassTranslation
{
use \Knp\DoctrineBehaviors\Model\Translatable\Translation;
/**
* @var string
*/
protected $description;
/**
* @return string
*/
public function getDescription()
{
return $this->description;
}
/**
* @param string $description
*
* @return MyClassTranslation
*/
public function setDescription($description)
{
$this->description = $description;
return $this;
}
现在调用MyClass::getDescription()将调用魔术方法,该方法__call()将使用当前语言环境返回翻译,因为.getDescription()MyClass
解决方案:
SportTranslation您应该从您的类中删除所有可翻译的 getter/setter/properties Sport,而是添加魔术__call()方法。
目前这是在管理列表模板中打印值的唯一方法。
如果您想要所有翻译,您可以简单地添加到您的运动管理类中:
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('translations')
}
这样,结果将取决于 SportTranslation 类的 __toString 函数。
否则,如果您想打印当前翻译,我想您应该使用自定义模板。例如,我将删除 Sport 中的 getNom 方法。
然后在你的运动管理类中:
protected function configureListFields(ListMapper $listMapper)
{
$listMapper
->addIdentifier('translations', null, array(
'template' => 'YourAdminBundle:CRUD:translatable.html.twig'
));
}
在您的模板中
{% extends 'SonataAdminBundle:CRUD:base_list_field.html.twig' %}
{% block field%}
{{ object }}
{% endblock %}
这样它就会调用你的运动类的 __toString 并且它可以在没有 getNom 方法的情况下工作。
不幸的是,它不能纠正我的问题链接到你的问题:如何使用 knplabs 教义行为在奏鸣曲管理员中对可翻译数据进行排序