Created
January 29, 2013 14:02
-
-
Save DuaelFr/4664453 to your computer and use it in GitHub Desktop.
How to use Drupal messages within an ajax call.
This file contains hidden or 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 | |
/** | |
* Implements hook_menu(). | |
*/ | |
function MYMODULE_menu() { | |
$items = array(); | |
$items['login'] = array( | |
'title' => t('Log in'), | |
'page callback' => 'drupal_get_form', | |
'page arguments' => array('MYMODULE_login_form'), | |
'access callback' => TRUE, | |
); | |
return $items; | |
} | |
//------------------------------------------------------------------------------ | |
// LOG IN FORM | |
//------------------------------------------------------------------------------ | |
/** | |
* Form MYMODULE_login_form callback. | |
*/ | |
function MYMODULE_login_form() { | |
$form = array(); | |
$form['messages'] = array( | |
'#markup' => '<div id="MYMODULE-login-form-messages"></div>', | |
'#type' => 'markup', | |
); | |
// Add other fields here | |
$form['submit'] = array( | |
'#type' => 'submit', | |
'#value' => t('Log in'), | |
'#ajax' => array( | |
'callback' => 'MYMODULE_login_callback', | |
'progress' => array( | |
'type' => 'throbber', | |
'message' => t('Please wait...'), | |
), | |
'effect' => 'fade', | |
), | |
); | |
return $form; | |
} | |
/** | |
* AjaX callback for the visustock_login_form submission. | |
*/ | |
function MYMODULE_login_callback($form, $form_state) { | |
$commands = array(); | |
$errors = form_get_errors(); | |
if (empty($errors)) { | |
// Do something here | |
} | |
return _MYMODULE_build_callback($form, $form_state, $commands); | |
} | |
//------------------------------------------------------------------------------ | |
// HELPERS | |
//------------------------------------------------------------------------------ | |
/** | |
* Generic callback | |
*/ | |
function _MYMODULE_build_callback($form, $form_state, array $commands) { | |
$target_id = _MYMODULE_get_target_id($form, $form_state); | |
$commands[] = ajax_command_html('#' . $target_id . '-messages', theme('status_messages'), array('effect' => 'fade')); | |
$commands[] = ajax_command_changed('#' . $target_id . '-messages'); | |
return array( | |
'#type' => 'ajax', | |
'#commands' => $commands, | |
); | |
} | |
/** | |
* Get target id from | |
*/ | |
function _MYMODULE_get_target_id($form, $form_state) { | |
$target_id = $form['#form_id']; | |
if (!empty($form_state['clicked_button']['#ajax']['wrapper'])) { | |
$target_id = $form_state['clicked_button']['#ajax']['wrapper']; | |
} | |
$target_id = strtr(drupal_strtolower($target_id), array(' ' => '-', '_' => '-', '[' => '-', ']' => '')); | |
return $target_id; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment