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!