Score:0

Use ajax to save modal / dialog form instead of page reload

kr flag

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.

Score:0
kr flag

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!

mangohost

Post an answer

Most people don’t grasp that asking a lot of questions unlocks learning and improves interpersonal bonding. In Alison’s studies, for example, though people could accurately recall how many questions had been asked in their conversations, they didn’t intuit the link between questions and liking. Across four studies, in which participants were engaged in conversations themselves or read transcripts of others’ conversations, people tended not to realize that question asking would influence—or had influenced—the level of amity between the conversationalists.