我目前在Symfony中有一个脚本,我在控制器中生成一个表单。此表单显示实体“页面”的内容。如果用户编辑表单并提交表单,则表单会调整数据库中的相应数据。
/**
* Webpage allowing user to edit a page and her attributes
*
* @Route("/edit")
*/
public function editAction(Request $request)
{
/*
* Get an array of all the current pages stored in the database.
*
* foreach loop through each website and create a seperate form for them
*
*/
$em = $this->getDoctrine()->getManager();
$pages = $em->getRepository(Page::class)->findAll();
foreach ($pages as $page) {
$editform= $this->createFormBuilder($page)
->add('name', 'text')
->add('location', 'url')
->add('displayTime', 'integer')
->add('save', 'submit', array(
'label' => 'Edit page'
))
->getForm();
$editform->handleRequest($request);
if ($editform->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->flush();
return new Response('Page edited successfully - immediately effective');
}
}
return $this->render('WalldisplayBundle:Walldisplay:edit.html.twig',
array(
'editform' => $editform->createView()
));
}
不幸的是,这只会打印一个包含数据库中最后一个条目的表单。我想要的是为数据库中的--every-条目创建一个表单,而不仅仅是最后一个。我试过迭代Doctrine存储库,但没有运气。我怎么能解决这个问题?
答案 0 :(得分:0)
也许它会奏效。我没有测试过。
/**
* Webpage allowing user to edit a page and her attributes
*
* @Route("/edit")
*/
public function editAction(Request $request)
{
/*
* Get an array of all the current pages stored in the database.
*
* foreach loop through each website and create a seperate form for them
*
*/
$em = $this->getDoctrine()->getManager();
$pages = $em->getRepository(Page::class)->findAll();
foreach ($pages as $key=>$page) {
$editforms[$key] = $this->createFormBuilder($page)
->add('name', 'text')
->add('location', 'url')
->add('displayTime', 'integer')
->add('save', 'submit', array(
'label' => 'Edit page'
))
->getForm();
foreach($editforms as $editform){
$editform->handleRequest($request);
if ($editform->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->flush();
}
}
return new Response('Page edited successfully - immediately effective');
}
foreach($editforms as $editform){
$editform->handleRequest($request);
if ($editform->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->flush();
}
foreach($editforms as $editform){
$arrayForm[$editform] = $editform->createView();
}
return $this->render('WalldisplayBundle:Walldisplay:edit.html.twig', $arrayForm);
}