php - Symfony2 - 在 CRUD 操作中使用删除表单

标签 php symfony symfony-forms symfony-2.8

由 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/

相关文章:

php - 获取准备好的mysql语句的结果

php - 让 Varnish 在 Magento 上工作

php - mySQL 在一个查询但三个表中使用复杂连接列出配置文件和电影

php - 从供应商类生成 Symfony2 表单

validation - 如何检查提供的 CSRF token 在 Symfony2 中是否无效?

php - Symfony2 表格 : Preselected value is lost in editAction

php - Linux - 我无法更改 NTFS 分区的其他读取或执行权限

php - 将自定义 Sonata 页面路由添加到导航栏

php - Symfony3如何在数据库中存储用户角色

database - 使用 doctrine2 测试 symfony2 的数据生成器