سؤال

The issue:

In Drupal 7's Form API, when using #AJAX to refresh fields, error messages from validation are not displayed until the entire page is refreshed. I see the field I refreshed highlighted in the error state, but the user does not see the associated message until it's too late (they've reloaded the page, or gone to another page).

I started to manually process the error stack in this manor: Drupal.org -- Filter out specific errors during validation, but I have a complex form, and a small budget of time to complete this task. There must be some way to refresh the stack & display the messages to the user without processing everything manually.

Note: I'm using multi-commands with a callback, so utilizing this is an option for me.

  $commands[] = ajax_command_replace("#my_wrapper", render($form['test']['field_a']));
  $commands[] = ajax_command_replace("#another_wrapper", render($form['test']['field_b']));

  return array('#type' => 'ajax', '#commands' => $commands);

Thoughts?

هل كانت مفيدة؟

المحلول

Solution:

Apparently, when you use the multi-callback approach, Drupal does not refresh messages for you. You can do this manually, as follows:

  // Remove the old messages div, clearing existing messages.
  $commands[] = ajax_command_remove('#messages');
  // Append a new messages div with our latest errors and messages.
  $commands[] = ajax_command_after('#header-region', '<div id="messages">' . theme('status_messages') . '</div>');

Simply add this to any callback commands[] array you have, and you're good to go.

Thanks to Drupal.org -- AJAX commands and Drupal Messages for the right direction!

نصائح أخرى

thanks atomox! just a fuller example for those not onto multi comands yet:

 $form['ld']['letterdrop_allocations_submit'] = array(
     '#type' => 'submit',
     '#value' => 'Letterdrop allocations update',
     //        '#name' => 'Letterdrop allocations update',
     '#name' => 'agc_letterdrop_submit',
     '#ajax' => array(
       'callback' => 'agc_ems_form_letterdrop_submit_ajax',
       ),
     );

 ...

function agc_ems_form_letterdrop_submit_ajax($form, &$form_state) { 
  drupal_set_message('here i am world', 'ok'); 
  $commands = array(); 
  $commands[] = ajax_command_replace('#messages', 
      '<div id="messages">' . theme('status_messages') . '</div>'); 
  $commands[] = ajax_command_alert('submitted via handler'); 
  return array( 
      '#type' => 'ajax', 
      '#commands' => $commands); 
} 

Also is a bit more concise and removes the assumptions that messages sit below the header region:

$commands[] = ajax_command_replace('#messages', '<div id="messages">' . theme('status_messages') . '</div>');
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top