Drupal 7 - #AJAX刷新不显示drupal_set_message错误

时间:2013-05-16 15:52:16

标签: ajax drupal drupal-fapi

问题:

在Drupal 7的Form API中,当使用#AJAX刷新字段时,在刷新整个页面之前,不会显示验证中的错误消息。我看到我刷新的字段在错误状态中突出显示,但用户没有看到相关的消息,直到它为时已晚(他们重新加载页面,或转到另一页)。

我开始在这个庄园中手动处理错误堆栈:Drupal.org -- Filter out specific errors during validation,但我有一个复杂的表单,而且预算时间很短,无法完成此任务。必须有一些方法来刷新堆栈和向用户显示消息而不手动处理所有内容。

注意: 我正在使用带有回调的多命令,因此利用它是我的选择。

  $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);

思想?

2 个答案:

答案 0 :(得分:5)

解决方案:

显然,当您使用多回调方法时,Drupal不会为您刷新消息。您可以手动执行此操作,如下所示:

  // 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>');

只需将此添加到您拥有的任何回调命令[]数组中,就可以了。

感谢Drupal.org -- AJAX commands and Drupal Messages正确的方向!

答案 1 :(得分:3)

谢谢atomox!对于那些尚未进入多指令的人来说,这只是一个更完整的例子:

 $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); 
} 

还有点简洁,并删除了消息位于标题区域下方的假设:

$commands[] = ajax_command_replace('#messages', '<div id="messages">' . theme('status_messages') . '</div>');