2

我已经使用“use-ajax”类在模式中呈现登录表单。我想在不关闭它的情况下处理同一模式上的验证错误。成功登录时,它会正确重定向,但是当发生错误时,它会关闭模式并重定向到登录页面,即用户/登录并在该页面上显示错误。我尝试使用 ajax 回调通过更改正在工作的表单来显示模态本身的错误。但是,它给了我 drupal ajax 错误。这是我的代码:

 $form['#prefix'] = '<div id="modal-form">';
     $form['#suffix'] = '</div>';
     $form['status_messages'] = [ 
           '#type' => 'status_messages',
                 '#weight' => -10,

     ];

     $form['actions']['submit']['#ajax'] = array(
         'callback' => 'setMessage',
         'wrapper' => 'modal-form',
     );

==================================================== ========================

function setMessage(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {
$response = new AjaxResponse();

 if ($form_state->hasAnyErrors()) {
     $response->addCommand(new ReplaceCommand('#modal-form', $form));

 }
 else {
     $command = new CloseModalDialogCommand('#modal-form', FALSE);
     $response->addCommand($command);

 }
 return $response;
}

上面的代码也给了我会话ID,但由于drupal ajax错误,它不会通过关闭模式重定向成功。

如果我使用非 ajax 即。如果我删除 ajax 回调函数,它会成功,但错误不会显示在模式上。

4

1 回答 1

2

首先,检查您是否在模块文件中使用 hook_login 添加了与重定向相关的更改。您可以删除与重定向相关的更改并在回调函数中处理重定向。

function setMessage(&$form, \Drupal\Core\Form\FormStateInterface $form_state) {

     $response = new AjaxResponse();
     $current= \Drupal::currentUser();
     if ($form_state->hasAnyErrors()) {
         $response->addCommand(new ReplaceCommand('#modal-form', $form));

     }
     else if (!$current->id()) {
         $response->addCommand(new ReplaceCommand('#modal-form', $form));
     }
     else {
         $command = new RedirectCommand(' ');

         return $response->addCommand($command);
     }
     return $response;
} 

成功后,它将关闭模式并正确重定向。如果您发现任何错误或未登录,它将保持模式形式。

于 2020-03-11T10:01:57.880 回答