0

I'm writing a backend validation function to prevent multiple submission for comments by logged in users in Drupal. Following is my code:

function MYMODULE_form_comment_form_alter( &$form, &$form_state, $form_id ) {
        if( user_is_logged_in() ) {
          $unique_bytes = openssl_random_pseudo_bytes( 8 );
          $unique_id = bin2hex( $unique_bytes );
          $session_key = 'comment_form_token_' . $form['form_id']['#id'];
          $_SESSION[$session_key] = $unique_id;
          $form['one_time_token'] = array(
              '#type' => 'hidden',
              '#value' => $unique_id,
          );
          $form['#validate'][] = '_MYMODULE_comments_validate_one_time_token';
        }
}
function _MYMODULE_comments_validate_one_time_token( $form, &$form_state ) {
  if( user_is_logged_in() ) {
    $form_id = $form['form_id']['#id'];
    $session_key = 'comment_form_token_' . $form_id;
    $one_time_token = $form_state['values']['one_time_token'];
    if( isset( $_SESSION[$session_key] ) && $_SESSION[$session_key] === $one_time_token ) {
      unset( $_SESSION[$session_key] );
    }
    else {
      form_set_error( 'comment_body', t( 'Please make sure that you have submitted this form only once.' ) );
    }
  }
}

The problem is that when the user submits the form multiple times by clicking the Submit button extremely fast, the one_time_token field's value gets updated automatically rather than submitting the original value.

To elaborate further, if my initial field value on form load was e8ac1824bf894e12, session value for that was also e8ac1824bf894e12 and submitted value was also e8ac1824bf894e12. But on processing second submission, my session value is 153695ec028bf151 but I expect my submitted values to stay e8ac1824bf894e12 but somehow that also changes to 153695ec028bf151.

Is there a way I can prevent that?

1
  • The session value seems to be unset on every form submission because your if statement is always true. Is this a common pattern to prevent multiple submissions? Why don't you just compare the content of the last comment by this user with the current one? Or you could compare the form request time (hidden value) with the submission time. – Philipp Michael Apr 25 '16 at 6:42
1

You can use jQuery to change the submit button to a loading gif when the save button is clicked. Thus, preventing any more clicks.

(function($) {
  $('.form-submit').click(function() {
     $('.form-submit').html('<img src="https://media.giphy.com/media/TtZqlvHid7BjW/giphy.gif">');
  });
})(jQuery);

JS Fiddle Example

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.