0

I'm looking for a way to save modal & dialog forms through ajax instead of redirecting the user after the form submit. Ajax is quite unknown territory to me.

I've found several interesting topics here already:

jQuery UI Dialog attempt to submit a form using AJAX redirects me to the actual form page instead of AJAX submitting

How to close modal after form submit?

I tried all answers shown there, but without luck. I'm using Drupal 9 and it seems that the code can be slightly different between 8 & 9 versions. I tried digging in the documentation pages on drupal.org but can't seem to find anything useful to my case.

0

For anyone who cares, I got it working with following code in my custom 'cs_modals' module:

 /**
 * Implements hook_form_alter().
 */
function cs_modals_form_alter(&$form, \Drupal\Core\Form\FormStateInterface $form_state, $form_id) {
    $request = \Drupal::request();
    // Check if Ajax request.
    if ($request->isXmlHttpRequest()) {
      $form['actions']['submit']['#ajax']['callback'] = '_cs_modals_id_submit_ajax_callback';
    }
}

/**
 * Custom Ajax callback.
 */
function _cs_modals_id_submit_ajax_callback(array &$form, FormStateInterface $form_state) {
  // If form is valid then close the dialog.
  if (!$form_state->hasAnyErrors()) {
    $response = new \Drupal\Core\Ajax\AjaxResponse();
    $response->addCommand(new \Drupal\Core\Ajax\CloseDialogCommand());
    return $response;
  }
  // Otherwise call the default #ajax callback.
  $form_object = $form_state->getFormObject();
  $response = $form_object->submitAjaxForm($form, $form_state) ;
  return $response;
}

Now, every form in a modal is submitted through Ajax. Now I'm looking for a way to automatically close the modal when the form is submitted succesfully or display an error message through Ajax when one or more required fields have no value. Any help on that would be appreciated!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.