symfony2 ContextErrorException:可捕获的致命错误:类Proxies__CG__..


symfony2 ContextErrorException: Catchable Fatal Error: Object of class Proxies__CG__...Entity... could not be converted to string

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

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

  • 类别
  • 用户
  • Post

我设置了这些关系,所有的事情都能很好地处理fixture数据(app/console doctrine:fixtures:load)。

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

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

当我更新一篇帖子时,我得到了一个奇怪的错误:

ContextErrorException:可捕获的致命错误:类Proxies__CG__的对象。。。''BlogBundle''Entity''Category无法转换为字符串

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

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

由于我指定了property选项,所以在Entity类中不需要__toString()

如果我创建一个像这样的__toString()(在类别和用户实体中),错误就消失了:

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

我不确定我做这件事的方式是否正确。

此外,由于Category&User对象被传递到category_iduser_id字段,Doctrine(或Symfony)应该能够计算出id列。我错过了什么?有其他方法吗?

我刚刚遇到了这个问题,并出现了上面提到的错误(最终出现在这里),我将发布对我有效的解决方案,因为没有其他答案。

和OP一样,我也创建了一个新的表,并使用条令加入。

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

向对象添加__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

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

这里有错误消息:选项"属性"不存在。。。

这是因为实体字段不再使用选项"属性"(文档)。

您应该使用选项"choice_label"。