I'm using the Webform module for Drupal 8. The module confirmation settings for a form are the following:
Page (redirects to new page and displays the confirmation message)
Inline (reloads the current page and replaces the webform with the confirmation message.)
Message (reloads the current page/form and displays the confirmation message at the top of the page.)
URL (redirects to a custom path or URL)
URL with message (redirects to a custom path or URL and displays the confirmation message at the top of the page.)
But how am I able to submit a form via AJAX so that the page doesn't reload on submit, but a confirmation message still replaces the form? What did I do wrong?
EDIT:
Here is the solution which works:
First you have to hook the form alter function and set an AJAX callback (as in echo's answer):
use \Drupal\Core\Form\FormStateInterface;
function MYTHEME_form_alter(&$form, FormStateInterface $form_state, $form_id)
{
if ( isset($form['#webform_id']) && $form['#webform_id'] == 'MYWEBFORM' )
{
// add an AJAX callback to the form submission
$form['actions']['submit']['#ajax'] = array(
'callback' => '\Drupal\MYMODULE\Controller\DefaultController::processFormSubmission',
'event' => 'click',
);
}
}
Then in the processFormSubmission
function you can process the form (put use \Drupal\Core\Form\FormStateInterface;
at the top of your file) like:
// Instantiate an AjaxResponse Object to return.
$ajax_response = new \Drupal\Core\Ajax\AjaxResponse();
/* do sth */
// in the DOM: replace the form with the text 'form submitted'
$ajax_response->addCommand(new \Drupal\Core\Ajax\HtmlCommand('#MYFORM', 'form submitted'));
return $ajax_response;
#ajax
on the submit form item, which calls a function that returns anAjaxResponse
with commands.