6

我在将实体保存回我时遇到了这个错误:

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()是实体类型!

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();
}
//...

另一个奇怪的事情是,如果我将 cascade ={"persist"} class MailTelCont 放在 ManyToOne 关系“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
            ))

我在哪里做错了?

4

1 回答 1

13

我认为那些价值观就是null那时。你试过了吗:

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

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

这样,当值null被转换为字符串时,你不应该得到这个异常。

于 2013-02-17T16:48:46.120 回答