You are here

public function WebformAjaxFormTrait::submitAjaxForm in Webform 8.5

Same name and namespace in other branches
  1. 6.x src/Form/WebformAjaxFormTrait.php \Drupal\webform\Form\WebformAjaxFormTrait::submitAjaxForm()

Submit form #ajax callback.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Return value

\Drupal\Core\Ajax\AjaxResponse An Ajax response that display validation error messages or redirects to a URL

1 method overrides WebformAjaxFormTrait::submitAjaxForm()
WebformUiElementTypeFormBase::submitAjaxForm in modules/webform_ui/src/Form/WebformUiElementTypeFormBase.php
Submit form #ajax callback.

File

src/Form/WebformAjaxFormTrait.php, line 190

Class

WebformAjaxFormTrait
Trait class for Webform Ajax support.

Namespace

Drupal\webform\Form

Code

public function submitAjaxForm(array &$form, FormStateInterface $form_state) {
  $scroll_top_target = isset($form['#webform_ajax_scroll_top']) ? $form['#webform_ajax_scroll_top'] : 'form';
  if ($form_state
    ->hasAnyErrors()) {

    // Display validation errors and scroll to the top of the page.
    $response = $this
      ->replaceForm($form, $form_state);
    if ($scroll_top_target) {
      $response
        ->addCommand(new WebformScrollTopCommand('#' . $this
        ->getWrapperId(), $scroll_top_target));
    }

    // Announce validation errors.
    $this
      ->announce($this
      ->t('Form validation errors have been found.'));
  }
  elseif ($form_state
    ->getResponse() instanceof AjaxResponse) {

    // Allow developers via form_alter hooks to set their own Ajax response.
    // The custom Ajax response could be used to close modals and refresh
    // selected regions and blocks on the page.
    $response = $form_state
      ->getResponse();
  }
  elseif ($form_state
    ->isRebuilding()) {

    // Rebuild form.
    $response = $this
      ->replaceForm($form, $form_state);
    if ($scroll_top_target) {
      $response
        ->addCommand(new WebformScrollTopCommand('#' . $this
        ->getWrapperId(), $scroll_top_target));
    }
  }
  elseif ($redirect_url = $this
    ->getFormStateRedirectUrl($form_state)) {

    // Redirect to URL.
    $response = $this
      ->createAjaxResponse($form, $form_state);
    $response
      ->addCommand(new WebformCloseDialogCommand());
    $response
      ->addCommand(new WebformRefreshCommand($redirect_url));
  }
  else {
    $response = $this
      ->cancelAjaxForm($form, $form_state);
  }

  // Add announcements to Ajax response and then reset the announcements.
  // @see \Drupal\webform\Form\WebformAjaxFormTrait::announce
  $announcements = $this
    ->getAnnouncements();
  foreach ($announcements as $announcement) {
    $response
      ->addCommand(new AnnounceCommand($announcement['text'], $announcement['priority']));
  }
  $this
    ->resetAnnouncements();
  return $response;
}