由 symfony 生成的自动 crud 操作以及 symfony 演示应用程序具有以下删除操作的代码结构
/**
* Deletes a testing entity.
*
* @Route("/{id}", name="testing_delete")
* @Method("DELETE")
*/
public function deleteAction(Request $request, testing $testing)
{
$form = $this->createDeleteForm($testing);
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {
$em = $this->getDoctrine()->getManager();
$em->remove($testing);
$em->flush();
}
return $this->redirectToRoute('testing_index');
}
/**
* Creates a form to delete a testing entity.
*
* @param testing $testing The testing entity
*
* @return \Symfony\Component\Form\Form The form
*/
private function createDeleteForm(testing $testing)
{
return $this->createFormBuilder()
->setAction($this->generateUrl('testing_delete', array('id' => $testing->getId())))
->setMethod('DELETE')
->getForm()
;
}
我的问题是为什么我们需要一个表格来删除?我们不能在 Twig 中有一个链接,并相应地设置一个 id
参数,我们不能只执行以下操作,为什么我们需要检查实体 isValid()
里面删除之前的表单?
/**
* test delete
* @Route("/{id}", name="testing_delete")
* @Method("DELETE")
*/
public function deleteAction(testing $testing) {
$em = $this->getDoctrine()->getManager();
$em->remove($testing);
$em->flush();
return $this->redirectToRoute('testing_showall');
}
最佳答案
如果您使用带有 id 的删除链接,机器人可能会循环删除您的数据。
在 Symfony 操作中检查“DELETE”方法以及您的 crsf token 是否使用方法 isValid“$form->isValid()”进行验证
这是创建表单和验证的安全原因
关于php - Symfony2 - 在 CRUD 操作中使用删除表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34605463/