Symfony2 exception when trying to embed a collecti

2019-08-26 11:28发布

问题:

A continuation of this question:

I'm trying to embed a collection of forms as described in the official docs here. Unfortunately, I'm getting the following exception:

The form's view data is expected to be an instance of class Acme\SiteBundle\Entity\BlogPost, but is a(n) array. You can avoid this error by setting the "data_class" option to null or by adding a view transformer that transforms a(n) array to an instance of Acme\SiteBundle\Entity\BlogPost.

Which is odd, as I believe I followed the official docs to a 't':

BlogPostType:

class BlogPostType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        // static text fields/attrs (title, body, etc)
        $builder->add('comments', 'collection', array('type' => new CommentType()));
    }

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

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array('data_class' => 'Acme\SiteBundle\Entity\BlogPost'));
    }
}

CommentType:

class CommentType extends AbstractType
{
    public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder->add('commentId', 'hidden');
        $builder->add('commentBody','text',array('label' => 'Comment:','attr'=>array('size'=>80,'class'=>'form-item-input form-type-texfield')));
    }

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

    public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array('data_class' => 'Acme\SiteBundle\Entity\Comment'));
    }
}

Relationship as defined in BlogPost:

/**
 * @var \Acme\SiteBundle\Entity\Comment.php
 *
 * @ORM\OneToMany(targetEntity="Comment", mappedBy="blogpost",
    cascade={"all"},orphanRemoval=true)
 * @ORM\OrderBy({"commentId" = "ASC"})
 */
private $comments;

And in Comment:

/**
 * @var BlogPost
 *
 * @ORM\ManyToOne(targetEntity="BlogPost", inversedBy="comments")
 * @ORM\JoinColumns({
 *   @ORM\JoinColumn(name="blog_id", referencedColumnName="id")
 * })
 */
private $blogPost;

So, I'm not sure where I've gone wrong. Any ideas?

回答1:

Turns out I was an idiot (big surprise there) and was passing the form builder an array. Old code that used to work was breaking it now. Whee!