【问题标题】:How to use KNP Translatable in a form type如何在表单类型中使用 KNP Translatable
【发布时间】:2015-05-19 09:41:18
【问题描述】:

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

用户(ID、姓名、电子邮件、密码...) 角色(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”类中访问。

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

【问题讨论】:

    标签: symfony translation


    【解决方案1】:

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

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

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

    1. 执行调用 proxyCurrentLocaleTranslation 的 getter 和 setter,恕我直言,使用不那么神奇的东西也没什么不好:)

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

      '属性' => '翻译[' . $options['locale'] 。 '].name',

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

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

    有关属性访问器的更多信息:

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

    关于第二种方式:

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

    【讨论】:

    • 嗨,非常感谢,看来我将使用选项 2。唯一的事情是我正在尝试注入会话对象以使用 getLocale 方法,但它看起来不再存在了。
    猜你喜欢
    • 1970-01-01
    • 2011-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-02
    • 2018-06-17
    相关资源
    最近更新 更多