Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I disable a Drupal form submit button when it is clicked to prevent double submission?

Sounds like a simple question. I've added a bit of jQuery magic:

$("#edit-save").click(function(event) {
  $(this).attr("disabled", "true");
});

However, once this is in place, my form submit handler doesn't get called.

This is a custom form on my own path defined in hook_menu:

$items['my_form'] = array(
  'title' => 'My form',
  'page callback' => 'drupal_get_form',
  'page arguments' => array('mymod_myform'),
  'type' => MENU_CALLBACK,
);

In the form, I have a submit button and a cancel button:

$form['cancel'] = array(
  '#type' => 'submit',
  '#value' => t('Cancel'),
);

$form['save'] = array(
  '#type' => 'submit',
  '#value' => t('Save'),
);

and I define my own submit handler:

$form['#submit'][] = 'mymod_myform_submit';

I've put a bit of tracing code in the drupal_get_form() function to sniff the $_POST variable when the form is submitted. When the jQuery magic is disabled, the $_POST variable includes an "op" parameter:

Array
  (
    [op] = Save
    [form_build_id] => form-6e74c87390e3fc48d0bebd2f5193315b
    [form_token] => 33db6e34c0350e33c48861a63a38d45f
    [form_id] => dh_seo_workload_item_form
  )

but if I enable the jQuery magic to disable the submit button after it's been clicked, the "op" parameter is no longer included in the $_POST array, and so Drupal thinks the form has not been submitted.

I've seen the question at Prevent double submission of forms in jQuery, but am concerned that this seems like a really hacky fix, and there should be a better way.

like image 996
Mark B Avatar asked Dec 17 '10 17:12

Mark B


People also ask

How Stop form submit on click of submit button?

We use the preventDefault() method with this event to prevent the default action of the form, that is prevent the form from submitting.

How do you disable form submit button until all input fields are filled?

Just click f12 in your browser, find the submit button in the html, and then remove the disabled ! It will submit the form even if the inputs are empty.

How do you submit form only once after multiple clicking on submit?

Disabling the Submit Button In practice this can cause a form to be submitted, or some other event triggered, more than once. The second button however will only accept a single click and ignore all subsequent clicks. The trick is to use JavaScript to set the disabled property of the button to true.


1 Answers

Or you can do this, as a one-liner addition at the PHP form array level...

$form['submit'] = array(
  '#type' => 'submit',
  '#value' => t('Save'),
  '#attributes' => array(
    'onclick' => 'javascript:var s=this;setTimeout(function(){s.value="Saving...";s.disabled=true;},1);',
  ),
);
like image 162
Nick Avatar answered Nov 15 '22 05:11

Nick