我想用从数据库加载的数据填写表单,让用户修改该数据。但是我遇到了下面的代码问题,选项1)按预期工作,但选项2)不想工作,表单是空的。如下所述'get_class'返回相同的类。 任何建议为什么选项1)工作和选项2)不?
public function editAction()
{
$document = new DocumentJourney();
$form = $this->createForm(new DocumentJourneyType(), $document);
$session = $this->getRequest()->getSession();
$journey_id = $session->get('journey_id');
$journey = $this->getDoctrine()->getRepository('PageBundle:JourneyDomesticShort')
->findOneById($journey_id);
$documents = $journey->getDocumentsJourney();
var_dump(get_class($document)); //
var_dump(get_class($documents[0])); /// shows the same class
// 1)
$document->setTravellerName($documents[0]->getTravellerName());
$form->setData($document); // this one works as expected
// 2)
$form->setData($documents[0]); // this one NOT work
return $this->render('PageBundle:Page:document_journey_edit.html.twig',
array('form' => $form->createView()));
}
更新:
我想我找到了一个解决方案:
public function editAction()
{
$session = $this->getRequest()->getSession();
$request = $this->getRequest();
$journey_id = $session->get('journey_id');
$journey = $this->getDoctrine()->getRepository('RedTapeProjectPageBundle:JourneyDomesticShort')
->findOneById($journey_id);
$documents = $journey->getDocumentsJourney();
$form = $this->createForm(new DocumentJourneyType(), $documents[0]);
return $this->render('PageBundle:Page:document_journey_edit.html.twig',
array('form' => $form->createView()));
}
该代码完成了我想要的但我认为前一个代码也可以正常工作。 有什么建议为什么前一个不起作用?