Posted by sahunt83 on December 13, 2012 at 9:59pm
Is it possible to prevent multiple form submissions server-side within Drupal 7?
I have followed the last answer in this post (it's a little hard to follow):
http://drupal.stackexchange.com/questions/22240/prevent-multiple-form-su...
Here is the relevant code within my two modules:
<?php
/**
* @file altform.install
*/
/**
* Implements hook_enable()
*/
function altform_enable(){
db_update('system')
->fields(array('weight' => -2000))
->condition('type', 'module')
->condition('name', 'altform')
->execute();
}
?><?php
/**
* @file altform.module
*/
/**
* Implements hook_form_alter()
*/
function altform_form_alter(&$form, &$form_state, $form_id){
$form['#validate'][] = 'altform_validate';
}
/**
* Validate
*/
function altform_validate(&$form, &$form_state){
if (!isset($_SESSION['posted_form'])){
$_SESSION['posted_form'] = array();
}
$form_token = $form_state['values']['form_id'];
if (isset($_SESSION['posted_form'][$form_token]) && $_SESSION['posted_form'][$form_token]==true){
form_set_error('', 'Form has already been submitted');
}
else {
$_SESSION['posted_form'][$form_token] = true;
}
}
/**
* Submit
*/
function altform_submit(&$form, &$form_state){
$form_token = $form_state['values']['form_id'];
unset($_SESSION['posted_form'][$form_token]);
}
?><?php
/**
* @file myform.module
*/
/**
* Implements hook_form_alter().
*/
function myform_form_alter(&$form, &$form_state, $form_id) {
$form['#submit'][] = 'altform_submit';
}
/**
* Form elements
*/
function myform_elements($form, &$form_state) {
// form elements...
}
/**
* Submit handler
*/
function myform_submit($form, &$form_state) {
// form submit...
}
?>With the above code in place, I am still able to submit multiple post by rapidly hitting the enter key or submit button.
This approach seems to have no affect until the page fully refreshes and the session gets set, then the conditional is met and I get the "Form has already been submitted" message.