1

尝试更新实体时出现以下异常:

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.

创建的时候没有问题,关系OK。但是,在更新时,出现了这个奇怪的异常。我的实体设置如下:

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 '';
    }
}

有什么想法吗,伙计们?

4

1 回答 1

4

问题是:

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

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

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

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

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

更多关于实体字段类型

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

于 2012-08-06T21:22:13.913 回答