Last active
December 16, 2015 07:08
-
-
Save bdecarne/5396262 to your computer and use it in GitHub Desktop.
Drupal : Add AJAX validation and submit to a regular form
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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; | |
} |
I have two notes which may be useful:
drupal_validate_form
method is called automatically if theform['#validate']
is populated- add
'event' => 'click'
to the$form['save']['#ajax']
array, it enables submitting by pressingENTER
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
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