【问题标题】:How do you define the getter to use in a CRUD form besides defining __toString()?除了定义 __toString() 之外,您如何定义要在 CRUD 表单中使用的 getter?
【发布时间】:2013-05-22 21:40:48
【问题描述】:

如果您使用 Symfony2 的生成器从数据库实体创建 CRUD 表单,您可能会在“创建新记录”屏幕上遇到类似这样的错误:

StringCastException: A "__toString()" method was not found on the objects of type
"ScrumBoard\ServiceBundle\Entity\Users" passed to the choice field. To read a
custom getter instead, set the option "property" to the desired property path.

如果我没看错,问题是它需要为我正在创建的记录显示用户的下拉列表,但它不知道如何将“用户”实体转换为字符串。

在我的 Users 实体类上定义 __toString() 方法解决了这个问题。但是,我可以从错误消息的文本中看到,还有一个替代方法:改为读取客户 getter,这是通过“[设置] 选项“属性”到所需的属性路径来完成的。”

这听起来像是某种注释。但在我的搜索中,我无法弄清楚那是什么。因为我想对 Symfony2 有一个透彻的了解——有人可以帮帮我吗?

谢谢!

【问题讨论】:

  • 在你的控制器的表单构建器调用中设置它
  • 对不起,我只是不知道这是什么意思。您是否有相关文档的链接或示例?

标签: symfony scaffolding


【解决方案1】:

在表单中创建实体(选择的超类)字段类型时。您需要指定标签/值应使用哪个属性,否则将使用基础对象的 __toString() 方法。

$builder->add('users', 'entity', array(
    'class' => 'AcmeHelloBundle:User',
    'property' => 'username',
));

entity field Type 的表单类型参考中了解更多信息。

其他信息

在模板中生成路由时,与 __toString() 相关的错误通常也来自 twig。 如果使用 {{ object }} ... twig 输出一个对象,则 twig 中的一个对象将调用该对象的 __toString 方法。 使用 SensioGeneratorBundle 生成的 crud 模板使用了这个“技巧”。

 {{ path('article_show', {'id': article}) }}

路线是这样的:

article_show:
   pattern:  /article/{id}
   defaults: { _controller: AcmeArticleBundle:Article:show }

如果您将 Article 实体中的 __toString 方法设置为...

 public function __toString()
 {
     return $this->id;
 }

...你不需要输入

{{ path('article_show', {'id': article.id) }}

如果你使用,一般Twig会自动输出Article::getId()

{{ article.id }}

希望这可以澄清您的发现。

【讨论】:

    猜你喜欢
    • 2016-03-19
    • 1970-01-01
    • 2018-02-15
    • 2012-08-29
    • 1970-01-01
    • 2011-12-18
    • 1970-01-01
    • 2018-12-06
    • 1970-01-01
    相关资源
    最近更新 更多