Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Symfony2 - use of Delete form in CRUD operation

the adutomatic crud operation generated by symfony and also the symfony demo application has the following code structure for the delete action

    /**
     * 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()
        ;
    }

my question is why do we need a form to delete? cant we just have a link in the twig with an id parameter set accordingly, cant we just do the following, why do we need to check if the entity isValid() inside a form before deleteing it?

    /**
     * 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');
    }
like image 349
pinch boi triggered af Avatar asked Jan 05 '16 06:01

pinch boi triggered af


1 Answers

If you used link for delete with id, it's possible to robot can delete you data with looping.

In Symfony action check "DELETE" method as well as if your crsf token verify with method isValid "$form->isValid()"

That's security reason it's create form and validate

like image 144
Ashok Chitroda Avatar answered Oct 09 '22 01:10

Ashok Chitroda