{Symfony2}使用数据填充表单

时间:2015-08-27 18:15:37

标签: php symfony

我对Symfony2中的表单有疑问。我尝试使用预先填充的数据来填充表单,但它始终保持空白。

public function updateAction($id,Request $request)
{

    $contact = $this->getDoctrine()
        ->getManager()
        ->getRepository('HPContactBundle:Contact')
        ->findById($id);

    $form = $this->createForm(new ContactType(), $contact);

    return $this->render('HPContactBundle:Contact:update.html.twig',array(
        'form' => $form->createView()
   ));
}

错误:

The form's view data is expected to be an instance of class HP\ContactBundle\Entity\Contact, 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 HP\ContactBundle\Entity\Contact.

at Form ->setData (array(object(Contact))) in vendor/symfony/symfony/src/Symfony/Component/Form/Form.php at line 488 

我不知道我错过了什么?你有什么线索吗?

提前thx。

1 个答案:

答案 0 :(得分:2)

findBy*()返回一组实体。使用findOneById(),它只返回一个实体。