What is the best way to add a “confirm-option” to a delete form in Symfony2?

穿精又带淫゛_ 提交于 2019-12-05 15:20:16

You could also render the basic delete-field of your form with an additional attribute:

Inside your Twig-Template:

{{ form(delete_form, {'attr': {'onclick': 'return confirm("Are you sure?")'}}) }}

Just use confirm javascript function on your delete link

<a href="{{ path('delete_route', {csrf:...}) }}" onclick="return confirm('are u sure?')">delete</a>

An issue with:

{{ form(delete_form, {'attr': {'onclick': 'return confirm("Are you sure?")'}}) }}

Is that it causes a double confirmation box to pop up. A better solution is to place it inside the controller on the deleteForm...

private function createDeleteForm($id)
{
    return $this->createFormBuilder()
        ->setAction($this->generateUrl('my_controller_delete', array('id' => $id)))
        ->setMethod('DELETE')
        ->add('submit', 'submit', array('label' => 'Delete',
                'attr' => array(
                        'onclick' => 'return confirm("Are you sure?")'
                )))
        ->getForm();
} 

Then the onclick function is on the button instead of the form.

A lightweight solution is to actually show your form twice: First, the user fills all fields. Then we recognise that it has not been confirmed already so we re-render it. This time the javascript immediately presents the confirmation dialog.

To this end we add a hidden field confirmed to the form and a parameter to the twig rendering:

$builder = $this->createFormBuilder(...);
$builder->add('confirmed', HiddenType::class, ['mapped' => false]);

$form = $builder->getForm();
$form->handleRequest($request);
if ($form->isSubmitted() && $form->isValid()) {

    if($form->get('confirmed')->getData() != true) { 
        // re-render with confirmation flag set
        return $this->render('default/form.html.twig', [
             'form' => $form->createView(),
             'confirm' => true]);
    }
} else {
    return $this->render('default/form.html.twig', [
         'form' => $form->createView(),
         'confirm' => false]);
}

And in your template to add a javascript like:

{{ form_start(form) }}
{{ form_widget(form) }}
{{ form_end(form) }}

<script>
$(document).ready(function () {
    var c = confirm('Really sure?');
    if(c) {
        $('#form_confirmed').val(true);
        $('form')[0].submit();

    }
});
</script>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!