Skip to content

Instantly share code, notes, and snippets.

@avblink
Created May 1, 2017 17:10
Show Gist options
  • Save avblink/0ba4b7a5d98e79b2b4e592f248e3d5a5 to your computer and use it in GitHub Desktop.
Save avblink/0ba4b7a5d98e79b2b4e592f248e3d5a5 to your computer and use it in GitHub Desktop.
Submit Drupal 8 webform via AJAX
<?php
function my_module_webform_submission_form_alter(array &$form, FormStateInterface $form_state, $form_id) {
if ($form['#webform_id'] == 'contact_an_expert') {
#$form['actions']['submit']['#validate'][] = 'wmp_content_types_contact_an_expert_form_validate';
$form['actions']['submit']['#ajax'] = [
'callback' => 'my_module_contact_an_expert_form_ajax',
'wrapper' => '.field--name-dynamic-block-fieldnode-contact-an-expert-form',
'type' => 'throbber',
];
}
}
function my_module_contact_an_expert_form_ajax(&$form, FormStateInterface $form_state) {
// Clear messages
$messages = drupal_get_messages();
// Check for validation errors
$errors = $form_state->getErrors();
if ($errors) {
// Set error classes
$form['elements']['first_name']['#attributes']['class'][] = 'custom-error-class';
}
else {
// Output empty form for new submission
_my_module_clear_webform_inputs($form, $form_state);
}
$response = new AjaxResponse();
$response->addCommand(new HtmlCommand($form['actions']['submit']['#ajax']['wrapper'], $form));
return $response;
}
function _my_module_clear_webform_inputs(array &$form, FormStateInterface $form_state) {
$form_id = $form['#form_id'];
$input = $form_state->getUserInput();
$clean_keys = $form_state->getCleanValueKeys();
// Remove input values
$clean_keys[] = 'ajax_page_state';
foreach ($input as $key => $item) {
if (!in_array($key, $clean_keys) && substr($key, 0, 1) !== '_') {
unset($input[$key]);
}
}
$form_state->setUserInput($input);
// Create new webform_submission entity
$webform_submission = \Drupal\webform\Entity\WebformSubmission::create([
'webform_id' => 'contact_an_expert',
]);
// Create entity form object and link it with the webform_submission entity
$entity_form_object = \Drupal::entityTypeManager()
->getFormObject('webform_submission', 'default');
$entity_form_object->setEntity($webform_submission);
// Set clean/new/without values form object to the current $form_state
$form_state->setFormObject($entity_form_object);
// Rebuild the form
$form = Drupal::formBuilder()->rebuildForm($form_id, $form_state);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment