Symfony 2 - Delete Forms and CSRF Token

后端 未结 3 1377
栀梦
栀梦 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

    The answer of @Lighthart led me to the correct answer:

    In your controller generate an array of form views and had it over to the view:

    public function indexAction()
    {
        $em = $this->getDoctrine()->getManager();
    
        $entities = $em->getRepository('AppBundle:Entity')->findAll();
    
        $delete_forms = array_map(
            function ($element) {
                return $this->createDeleteForm($element->getId())->createView();
            }
            , $entities
        );
    
        return $this->render('AppBundle:Entity:index.html.twig', array(
            'entities' => $entities,
            'delete_forms' => $delete_forms
        ));
    }
    

    Now you have to access this in your view. Therefore you can use the form functions and the special loop variables:

    {% extends '::base.html.twig' %}
    
    {% block body %}
        {% for entity in entities %}
            {# Access the delete form for this entity using the loop index ... #}
            {% set delete_form = delete_forms[loop.index0] %}
    
            {# ... and display the form using the form tags. #}
            {{ form_start(delete_form) }}
                
            {{ form_end(delete_form) }}
        {% endfor %}
    {% endblock %}
    

    That's it.

提交回复
热议问题