Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

If you create CRUD-code for an entity in Symfony2 using the console, you will end up with a very basic delete function.

This function is lean and efficient, but does not provide an "are you sure?"-confirmation. If the entity to be deleted exists, it will be deleted immediately.

Does anyone have suggestions for the easiest way to add user confirmation?

Up until now I have been using:

  • An extra controller function
  • jQuery

It seems a bit weird though that Symfony2 would have no built-in option for this. Anyone better ideas?

like image 664
Paul Maclean Avatar asked Dec 12 '12 08:12

Paul Maclean


3 Answers

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?")'}}) }}
like image 144
jpbaxxter Avatar answered Nov 11 '22 11:11

jpbaxxter


Just use confirm javascript function on your delete link

<a href="{{ path('delete_route', {csrf:...}) }}" onclick="return confirm('are u sure?')">delete</a>
like image 21
rpayanm Avatar answered Nov 11 '22 12:11

rpayanm


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.

like image 36
Cathmor Avatar answered Nov 11 '22 13:11

Cathmor