modal-dialogdrupal-8drupal-ajax

Drupal-8 Modal does not handle errors on login


I have used 'use-ajax' class to render login form in a modal. I want to handle validation errors on same modal without closing it. On successful login it is redirecting correctly, but when an error occurs it closes modal and redirecting to login page i.e user/login and displaying errors on that page. I tried to use ajax callback to display error on modal itself by altering the form which is working. But, it is giving me drupal ajax error. Here is my code :

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

The above code giving me session id also but due to drupal ajax error it does not redirect on success by closing modal.

If I go with non-ajax ie. if I remove the ajax callback function it works on success but errors are not displaying on modal.


Solution

  • First, check if you have added redirection related changes using hook_login in your module file. You can remove that redirection related changes and handle redirection in your callback function.

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

    On success it will close the modal and will redirect correctly. If you found any error or if you are not logged in it will stay on modal form.