3

如果您使用 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 有一个透彻的了解——有人可以帮帮我吗?

谢谢!

4

1 回答 1

11

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

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

在实体字段 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 }}

希望这能澄清你的发现。

于 2013-05-23T01:28:44.100 回答