Symfony2 __toString()错误

时间:2013-02-17 16:35:49

标签: symfony doctrine-orm symfony-2.1

我遇到了将实体保存回给我这个错误的问题:

Catchable Fatal Error: Method My\BusinessBundle\Entity\Type::__toString() 
must return a string value in
/var/www/MyBusiness0_1/vendor/doctrine/orm/lib/Doctrine/ORM/ORMInvalidArgumentException.php line 113

奇怪的是方法__ toString()是实体Type!

class Type
{
 //..

/**
 * @var string
 *
 * @ORM\Column(name="type", type="string", length=100)
 */
private $type;

/**
 * @ORM\OneToMany(targetEntity="MailTelCont", mappedBy="type")
 */
protected $mailTelContacts;

public function __construct()
{
    $this->mailTelContacts = new \Doctrine\Common\Collections\ArrayCollection();
}

public function __toString()
{
    return $this->getType();
}
//...

另一个奇怪的事情是,如果我在ManyToOne上放置cascade = {“persist”}类MailTelCont“type”并没有向我显示此错误,而是在Type中保存一个新字段..

类MailTelCont

class MailTelCont
{
 //..
/**
 * @var string
 *
 * @ORM\Column(name="contact", type="string", length=100)
 */
private $contact;

/**
 * @ORM\ManyToOne(targetEntity="Type", inversedBy="mailTelContacts")
 * @ORM\JoinColumn(name="type_id", referencedColumnName="id")
 */
private $type;

/**
 * @ORM\ManyToOne(targetEntity="Anagrafica", inversedBy="mailTelContacts", cascade={"persist"})
 * @ORM\JoinColumn(name="anagrafica_id", referencedColumnName="id")
 * @Assert\Type(type="My\BusinessBundle\Entity\Anagrafica")
 */
private $anagrafica;

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

以这种方式调用嵌套的“AnagraficType”形式:

class TypeType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('type', 'entity', array(
                'class' => 'My\BusinessBundle\Entity\Type',
                'attr' => array('class' => 'conct'),
                'property' => 'type',
                'label' => 'Tipologia',
        ))
    ;
}
*****
class MailTelContType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder
        ->add('type', new TypeType())
        ->add('contact', 'text', array('label' => 'Contatto'))                
    ;
}
*****
class AnagraficaType extends AbstractType
{
public function buildForm(FormBuilderInterface $builder, array $options)
{
    $builder->add('mailTelContacts', 'collection', array('type' => new MailTelContType(), 
                'allow_add' => true,
                'allow_delete' => true,
                'prototype' => true,
                'by_reference' => false
            ))

我在哪里做错了?

1 个答案:

答案 0 :(得分:13)

我认为这些值是null。你试过了吗?

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

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

当值为null时,这种方法将被转换为字符串,您不应该得到此异常。