symfony2 ContextErrorException:Catchable Fatal Error:类Proxies \ __ CG __ \ ... \ Entity \ ...的对象无法转换为字符串

时间:2014-04-20 19:20:29

标签: php symfony orm doctrine tostring

我遇到了一些奇怪的事情:

我通过app/console doctrine:generate:entity创建了三个学说实体:

  • 分类
  • 用户

我建立了关系,一切都适用于灯具数据(app/console doctrine:fixtures:load)。

帖子属于单个类别(category_id),并且有一个作者(user_id)。

我使用app/console doctrine:generate:crud来获取所有实体的CRUD操作。

当我更新帖子时,我收到了这个奇怪的错误:

  

ContextErrorException:Catchable Fatal Error:类Proxies__CG __... \ BlogBu​​ndle \ Entity \ Category的对象无法转换为字符串

为了正确显示我在PostType()中使用的下拉字段:

$builder ....
  ->add('categoryId','entity', array(
     'class' => 'HotelBlogBundle:Category',
     'property'=>'name'
))
->add('userId','entity',array(
     'class'=>'UserBundle:User',
     'property'=>'username'
))

由于我指定了property选项,因此我的实体类中不需要__toString()

如果我像这样创建一个__toString()(在类别和用户实体中都有),错误就会消失并且有效:

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

我不确定我是否以正确的方式做到了。

此外,由于Category& User对象传递给category_iduser_id字段,Doctrine(或Symfony)应该能够找出id列。我错过了什么?还有另一种方法吗?

2 个答案:

答案 0 :(得分:11)

我刚刚遇到上述错误遇到了这个问题(并在此处结束),我将发布对我有用的解决方案 - 因为没有其他答案。

与OP一样,我也使用Doctrine创建了一个新表并加入。

此错误告诉我们,已加入的object无法转换为string。我们必须在对象中提供__toString()方法,以便将其转换为字符串,或者我们可以使用property键指定我们要在表单构建器中返回哪个字段。

向对象添加__toString()方法

/**
 * (Add this method into your class)
 *
 * @return string String representation of this class
 */
public function __toString()
{
    return $this->name;
}

或者将属性键添加到表单构建器

// where `name` equals your field name you want returned
$builder->add('category', null, ['property' => 'name'])

我只是将__toString()方法添加到我的entity,我只有字段idname - 因此唯一的字符串表示形式是name

答案 1 :(得分:4)

在symfony 3中,你不能使用属性。

这里出现错误信息:选项"属性"不存在。 ...

这是因为实体字段没有使用选项" property"不再(documentation)。

你应该使用选项" choice_label"代替。