Symfony 2 - Delete Forms and CSRF Token

后端 未结 3 1173
栀梦
栀梦 2021-02-15 16:48

I have a List of entries coming from a database. I would like to have a \"Delete-Button\" at the end of every row, so that the user won\'t have to first go to the edit/show page

3条回答
  •  清酒与你
    2021-02-15 17:54

    I faced a similar situation where I wanted to delete a product while using csrf protection. I also wanted to use ajax to make the DELETE request.

    Tested for Symfony 3.x

    So, to do this, this is what my view, index.html, looked like:

    // html for displaying a products table with delete btn for each row
    // ...
    // Retrieve csrf token and store it somewhere in DOM (preferably outside table), 
    // We do this so that we can send the token via ajax later
     
    
    

    As seen above, {{ csrf_token('form') }} is what is actually giving you the csrf token inside twig.

    My Controller:

    /**
     * Deletes a product entity.
     * @Route("/{id}", name="admin_product_delete")
     * @Method("DELETE")
     */
    public function deleteAction(Request $request, product $product)
        {
            $form = $this->createDeleteForm($product);
            $form->handleRequest($request);
            if ($form->isSubmitted() && $form->isValid()) {
                $em = $this->getDoctrine()->getManager();
                $em->remove($product);
                $em->flush($product);
                // you can return a json response here to your ajax callback if you'd like.
                return new JsonResponse(array('status' => 'deleted'));
            }
        // return new JsonResponse(array('status' => 'failed'));
    }
    
    /**
     * Creates a form to delete a product entity.
     * @param product $product The product entity
     * @return \Symfony\Component\Form\Form The form
     */
    private function createDeleteForm(product $product)
    {
        return $this->createFormBuilder()
            ->setAction($this->generateUrl('admin/product/{id}', array('id' => $product->getId())))
            ->setMethod('DELETE')
            ->getForm()
        ;
    }
    

    And this should delete the required row as expected!

提交回复
热议问题