Skip to content

Instantly share code, notes, and snippets.

@bdecarne
Last active December 16, 2015 07:08
Show Gist options
  • Save bdecarne/5396262 to your computer and use it in GitHub Desktop.
Save bdecarne/5396262 to your computer and use it in GitHub Desktop.
Drupal : Add AJAX validation and submit to a regular form
<?php
function MY_MODULE_form_alter(&$form, &$form_state, $form_id)
{
$form['#prefix'] = '<div id="formwrapper">';
$form['#suffix'] = '</div>';
// the submit button
$form['save']['#ajax'] = array(
'callback' => 'MY_MODULE_form_ajax_submit',
'wrapper' => 'formwrapper',
'method' => 'replace',
'effect' => 'fade',
);
}
function MY_MODULE_form_ajax_submit($form, &$form_state)
{
// validate the form : ONLY IF NECESSARY
// drupal_validate_form('mymodule_form_id', $form, $form_state);
// if there are errors, return the form to display the error messages
if (form_get_errors()) {
$form_state['rebuild'] = TRUE;
return $form;
}
// process the form : ONLY IF NECESSARY
//mymodule_form_id_submit($form, $form_state);
$output = array('#markup' => '<div class="messages status">'.t('Your request has been processed').'</div>');
// return the confirmation message
return $output;
}
@PowerMugen
Copy link

Hi, I have a question about this snippet, It works fine but I have no submissions saved in the webform results.
They are saved when I deactivate this code.
Can you help me find what I'm doing wrong ?

Thanks for posting this

@andreicojea
Copy link

I have two notes which may be useful:

  1. drupal_validate_form method is called automatically if the form['#validate'] is populated
  2. add 'event' => 'click' to the $form['save']['#ajax'] array, it enables submitting by pressing ENTER key and it also fixes autocompletion issues

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment