Symfony2中的实体表单类型

时间:2015-12-03 17:13:40

标签: forms rest symfony fosrestbundle

我试图制作一个RESTFUL api,当我处理PUT时,它总是回应我

{
    "code": 500, 
    "message": "The form's view data is expected to be an instance of class My\\Bundle\\Entity\\Post, 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 My\\Bundle\\Entity\\Post."
}

以下是我编写PUT操作的方法。

public function putPostAction($postKey, Request $request){
    $post = $this->getDoctrine()->getManager()->getRepository('MyBundle:Post')
        ->findPost($postKey);
    $form = $form = $this->createFormBuilder($post,
        array('data_class' => 'My\Bundle\Entity\Post'))->getForm();
    // or use createForm like
    // $form = $this->createForm(new PostType(), $post);
    $form->submit($request);
    if($form->isValid()){
        $em = $this->getDoctrine()->getManager();
        $em->persist($post);
        $em->flush();
        return $post;
    }
    return array(
        "form" => $form
    );
}

说实体类型,看起来像

public function buildForm(FormBuilderInterface $builder, array $options)
    {
        $builder
            ->add('cityKey')
            ->add('status')
            ->add('text')
            ->add('imageKey')
            ->add('createTime')
            ->add('updateTime')
        ;
    }
/**
 * @param OptionsResolverInterface $resolver
 */
public function setDefaultOptions(OptionsResolverInterface $resolver)
{
    $resolver->setDefaults(array(
        'data_class' => 'My\Bundle\Entity\Post',
        'csrf_protection' => false
    ));
}

/**
 * @return string
 */
public function getName()
{
    return '';
}

关于错误消息,我将解析器修改为

public function setDefaultOptions(OptionsResolverInterface $resolver)
    {
        $resolver->setDefaults(array(
            'data_class' => null,
            'csrf_protection' => false
        ));
    }

这次我又遇到了一个错误,

{
    "code": 500, 
    "message": "EntityManager#persist() expects parameter 1 to be an entity object, array given."
}

有什么想法吗?提前谢谢。

1 个答案:

答案 0 :(得分:0)

findPost函数返回的对象数组不是object。您应该调用find($id)而只返回一个Post对象。

所以它应该是:

$post = $this->getDoctrine()->getManager()
             ->getRepository('MyBundle:Post')
             ->find($postKey);