在Symfony 2和Doctrine中设置ManyToOne关系时出现奇怪的异常

时间:2012-08-06 20:28:56

标签: php symfony doctrine

尝试更新实体时,我收到以下异常:

The form's view data is expected to be of type scalar, array or an instance of \ArrayAccess, but is an instance of class Proxies__CG__\Acme\DemoBundle\Entity\TicketCategory. You can avoid this error by setting the "data_class" option to "Proxies__CG__\Acme\DemoBundle\Entity\TicketCategory" or by adding a view transformer that transforms an instance of class Proxies__CG__\Acme\DemoBundle\Entity\TicketCategory to scalar, array or an instance of \ArrayAccess.

创建时,不会出现问题且关系正常。但是,在更新时,会出现这种奇怪的异常。我的实体设置如下:

class Ticket
{
    // ...

    /**
    * @var TicketCategory
    *
    * @ORM\ManyToOne(targetEntity="TicketCategory")
    * @ORM\JoinColumn(name="category_id", referencedColumnName="id")
    */
    protected $category;

    // ...
}

class TicketCategory
{
    /**
     * @var integer $id
     *
     * @ORM\Column(name="id", type="integer")
     * @ORM\Id
     * @ORM\GeneratedValue(strategy="AUTO")
     */
    private $id;

    /**
     * @var string $title
     *
     * @ORM\Column(name="title", type="string", length=255)
     * @Assert\NotBlank()
     */
    private $title;

    // ...
}

表格

class TicketType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('title', 'text', array(
                    'error_bubbling' => true,
                )
            )
            ->add('category', 'text', array(
                    'error_bubbling' => true,
                )
            )
        ;
    }

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => 'Acme\DemoBundle\Entity\Ticket',
            'csrf_protection' => false,
        ));
    }

    public function getName()
    {
        return '';
    }
}

任何想法,伙计们?

1 个答案:

答案 0 :(得分:4)

问题是:

    $builder
        ->add('category', 'text', array(
                'error_bubbling' => true,
            )
        )
    ;

字段category声明为“text”类型,因此您只能将标量(字符串,bool等)传递给它。也就是说,您只能指定属于标量的属性(Ticket类)。

Ticketcategory中,它是一个实体,因此会发生错误。

在不知道你想要完成什么的情况下,我想你想让用户选择一张票的类别,所以我会这样做:

    $builder
        ->add('category', 'entity', array(
                'label'    => 'Assign a category',
                'class'    => 'Acme\HelloBundle\Entity\TicketCategory',
                'property' => 'title',
                'multiple' => false
            )
        )
    ;

更多关于entity field type

编辑:不知道您是否省略了它,但Ticket没有名为“title”的属性。