如何在表单类型中使用KNP可翻译

时间:2015-05-19 09:41:18

标签: symfony translation

我正在使用KNP Translatable,我有以下数据结构:

用户(身份证,姓名,电子邮件,密码......) 角色(id,名称@translatable)

用户角色是多对多的关系。

我的表单类型定义如下:

->add('roles', 'entity', [
    'class' => 'SocialCarBackendBundle:Role',
    'property' => 'name',
    'multiple' => true,
    'expanded' => true
])

我在角色实体中实现了__call方法:

public function __call($method, $arguments)
    {
        try {
            return $this->proxyCurrentLocaleTranslation($method, $arguments);
        } catch (\Symfony\Component\Debug\Exception\ContextErrorException $e) {
            return $this->proxyCurrentLocaleTranslation('get' . ucfirst($method), $arguments);
        }

    }

现在,在twig模板中,我可以毫无问题地调用角色的name属性,并且可以正确呈现它。

但是在尝试渲染表单时,我收到了这个错误:

  

属性“name”和方法“getName()”之一,   “name()”,“isName()”,“hasName()”,“_ _ get()”存在并公开   访问类“SocialCar \ BackendBundle \ Entity \ Role”。

这有什么解决方法吗?非常感谢

1 个答案:

答案 0 :(得分:3)

symfony的propertyaccessor组件没有为EntityType属性启用魔术调用

你可以看到vendor / symfony / symfony / src / Symfony / Bridge / Doctrine / Form / Type / DoctrineType.php来证明这一点。

所以你有三种方式(按复杂程度排列):

  1. 做调用proxyCurrentLocaleTranslation的getter和setter,imho使用不太神奇的东西没什么不好的。)

  2. 使用像这样的更复杂的属性

    '属性' => '翻译[' 。 $ options [' locale']。 '。]名称',

    其中$ options [' locale']是作为选项在表单中注入的语言环境

  3. 您可以创建一个不同的EntityType类,扩展您的自定义DoctrineType类,初始化PropertyAccessor以支持魔术调用

  4. 有关属性访问者的更多信息:

    http://symfony.com/doc/current/components/property_access/introduction.html

    关于第二种方式:

    https://github.com/KnpLabs/DoctrineBehaviors/issues/67