Seeing dpm or drupal set message when using AJAX
Problem
One of the worst head-aches you'll encounter with AJAX is the inability to know if the code you're writing works.
Reason
This is because there's no place for the drupal_set_message() or dpm() messages to show on the screen.
Solution
This is easily fixed by the code below: I included a complete working copy so you get a better sense of what is going on.
/**
* Implements hook_form_alter().
*/
function hook_form_alter(&$form, &$form_state, $form_id) {
// Check if ajax was fired.
if (isset($form_state['triggering_element'])) {
// We can do remote calls or execute Drupal
// related functions.
drupal_set_message(t('This will show within #message-container.'));
}
$form['add_new_agency'] = array(
'#type' => 'textfield',
'#title' => t('Add new agency'),
'#default_value' => '',
'#ajax' => array(
'callback' => 'add_new_agency_ajax_callback',
'wrapper' => 'test-wrapper',
'#prefix' => '<div id="test-wrapper">',
'#suffix' => '</div>',
),
);
// Create an area where the ajax callback can write Drupal
// messages to.
$form['message_area'] = array(
'#type' => 'container',
'#prefix' => '<div id="message-container">',
'#suffix' => '</div>',
);
}
/**
* Ajax callback but more importantly, shows messages!
*/
function add_new_agency_ajax_callback($form, $form_state) {
$commands[] = ajax_command_remove('#message-area');
$commands[] = ajax_command_after('#message-container', '<div id="message-area">' . theme('status_messages') . '</div>');
return array('#type' => 'ajax', '#commands' => $commands);
}
Further Explanation
Notice line 27: $form['message_area'] array and line 37: add_new_agency_ajax_callback function. Now if you use DPM or a drupal_set_message and your ajax is triggered, you'll see the results in $form['message_area'].
Leave a comment