我有一个来自数据库的条目列表.我想在每一行的末尾都有一个“删除按钮”,这样用户就不必首先进入编辑/显示页面来删除该条目.
我尝试使用csrf标记创建一个隐藏的输入字段,如下所示:
return $this->createFormBuilder() ->getForm() ;
这将输出:
<div id="form"> <input type="hidden" id="form__token" name="form[_token]" value="6c98ebfa9df07....."> </div>
表单的其余部分放在twig模板中,以便每个表单根据条目的id有自己的操作路径.
不幸的是在树枝模板中只有第一个
{{ form_widget(delete_form) }}
将被渲染.
我怎样才能更频繁地使用这个隐藏的字段?
或者有没有办法以不同的方式完成这一切?
谢谢你的帮助
public function indexAction() { $em = $this->getDoctrine()->getManager(); $deleteForm = $this->createDeleteForms(); $entities = $em->getRepository('IntranetServicesBundle:Laender')->findAll(); return $this->render('IntranetServicesBundle:Laender:index.html.twig',array( 'entities' => $entities,'delete_form' => $deleteForm->createView(),)); } private function createDeleteForms() { return $this->createFormBuilder() ->add('id','hidden') ->getForm() ; }
您可以使用以下内容呈现单个令牌:
{{ form_widget(form._token) }}
或特别针对您的情况:
{{ form_widget(delete_form._token) }}
但是,我认为你可以更好地制作一系列表格并完全呈现每一个表格:
在你的控制器中:
public function indexAction() { $em = $this->getDoctrine()->getManager(); $rep= $em->getRepository('IntranetServicesBundle:Laender') ->createQueryBuilder('l'); var_dump($rep->getQuery()->getDql()); $entities=$rep->getQuery()->getResult(); $delete_forms = array_map( function($element){ return $this->createDeleteForm($element->getId());},$entities->toArray() ); return $this->render('IntranetServicesBundle:Laender:index.html.twig',array( 'entities' => $entities,'delete_forms' => $delete_forms )); } private function createDeleteForms($id) { return $this->createFormBuilder(array('id' => $id))) ->add('id','hidden') ->getForm() ; } public function deleteAction(Request $request,$id) { $form = $this->createDeleteForm($id); $form->bind($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $entity = $em->getRepository('IntranetServicesBundle:Laender') ->find($id); // this line might need to be changed to point to the proper repository if (!$entity) { throw $this->createNotFoundException('Unable to find Laender entity.'); } $em->remove($entity); $em->flush(); } return $this->redirect($this->generateUrl('laender_index')); // this line might need to be changed to point to the proper // post-delete route }
在你的树枝上做一些事情:
{% for form in delete_forms %}{{form_widget(form)}}{% endfor %}