class 的 Symfony 3 对象无法转换为字符串

Symfony 3 Object of class could not be converted to string

我有这个地址表。一切都按预期进行,直到我为城市添加了一个下拉选择字段。当我尝试保存表单时出现此错误:

Catchable Fatal Error: Object of class AppBundle\Entity\Address could not be converted to string

文档说 EntityType 字段旨在从 Doctrine 实体加载选项。

这是表格:

 $builder
             ->add('cities', EntityType::class, array(
                'class' => \AppBundle\Entity\Cities::class,
                'choice_label' => 'cityname',
                'choice_value' => 'cityid')
            )

这是我的实体

 /**
 * @var string
 * 
 * @ORM\Column(name="cities", type="string", length=55, nullable=false)
 */
private $cities;   

和setters/getters:

 /**
 * Set cities
 *
 * @param string $cities
 *
 * @return Address
 */
public function setCities($cities)
{
    $this->cities = $cities;

    return $this;
}

/**
 * Get cities
 *
 * @return string
 */
public function getCities()
{
    return $this->cities;
}

我还添加了这个:

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

结果是这样的:

Catchable Fatal Error: Method AppBundle\Entity\Address::__toString() must return a string value

您应该为实体实现 __toString() 方法:

__toString() allows a class to decide how it will react when it is treated like a string. For example, what echo $obj; will print. This method must return a string, as otherwise a fatal E_RECOVERABLE_ERROR level error is emitted.

例如,您可以编写类似这样的内容来将您的 class 表示为字符串:

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

有关此魔术方法的更多信息 here

该错误意味着您的 toString 方法返回的不是字符串(可能是一个以名称命名的数组?)。您可能想尝试检查数据以确定它是什么数据类型。

虽然 choice_label 选项比使用 toString 更好 - 它告诉 Symfony 实体中的 属性 应该映射到标签。