0

In my controller there is a rather classic action "create" based on Doctrine CRUD generation.

But when I execute this action by clicking the "create" form button several times the same object is created as many times as I clicked.

This is a major problem because my class "Operation" is quite large and takes a long time to record. The user is very tempted to click several times.

 /**
 * Creates a new Operation entity.
 *
 * @Route("/", name="operation_create")
 * @Method("POST")
 * @Template("MyApplicationBundle:Operation:new.html.twig")
 */
public function createAction(Request $request)
{
    $entity  = new Operation();
    $form = $this->createForm(new OperationType(), $entity, array(
        'em' => $this->getDoctrine()->getManager(),
    ));
    $form->bind($request);

    if ($form->isValid()) {
        $em = $this->getDoctrine()->getManager();
        $entity->setdateCreation(new \DateTime())
               ->setUser($this->get('security.context')->getToken()->getUser());
        $em->persist($entity);
        $em->flush();
        $this->get('session')->getFlashBag()->add('success', 'OK');
        return $this->redirect($this->generateUrl('operation_show', array('id' => $entity->getId())));
    }
    return array(
        'entity' => $entity,
        'form'   => $form->createView(),
    );
}

If anyone can help me it would be really nice.

Antoine Subit
  • 9,803
  • 4
  • 36
  • 52
  • 1
    disable the button after the first click via javascript? – Ken Hannel Jan 28 '14 at 17:21
  • possible duplicate http://stackoverflow.com/questions/926816/how-to-prevent-multiple-form-submit-from-client-side http://stackoverflow.com/questions/2830542/prevent-double-submission-of-forms-in-jquery – zizoujab Jan 28 '14 at 21:02

1 Answers1

2

After click on create button you must disabled or remove them with JavaScript, and user can't click second time at it.

If you use jQuery:

<input type="submit" onclick="jQuery(this).attr('disabled', 'disabled')">
Victor Bocharsky
  • 11,930
  • 13
  • 58
  • 91