You are here

protected function WebformAjaxFormTrait::buildAjaxForm in Webform 8.5

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

Add Ajax support to a form.

Parameters

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

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

array $settings: Ajax settings.

Return value

array The form with Ajax callbacks.

4 calls to WebformAjaxFormTrait::buildAjaxForm()
WebformDialogFormTrait::buildDialogForm in src/Form/WebformDialogFormTrait.php
Add modal dialog support to a form.
WebformEntityAjaxFormTrait::buildForm in src/Form/WebformEntityAjaxFormTrait.php
WebformSubmissionForm::buildForm in src/WebformSubmissionForm.php
Form constructor.
WebformUiEntityElementsForm::buildForm in modules/webform_ui/src/WebformUiEntityElementsForm.php
Form constructor.

File

src/Form/WebformAjaxFormTrait.php, line 124

Class

WebformAjaxFormTrait
Trait class for Webform Ajax support.

Namespace

Drupal\webform\Form

Code

protected function buildAjaxForm(array &$form, FormStateInterface $form_state, array $settings = []) {
  if (!$this
    ->isAjax()) {
    return $form;
  }

  // Apply default settings.
  $settings += $this
    ->getDefaultAjaxSettings();

  // Add Ajax callback to all submit buttons.
  foreach (Element::children($form) as $element_key) {
    if (!WebformElementHelper::isType($form[$element_key], 'actions')) {
      continue;
    }
    $actions =& $form[$element_key];
    foreach (Element::children($actions) as $action_key) {
      if (WebformElementHelper::isType($actions[$action_key], 'submit')) {
        $actions[$action_key]['#ajax'] = [
          'callback' => '::submitAjaxForm',
          'event' => 'click',
        ] + $settings;
      }
    }
  }

  // Add Ajax wrapper with wrapper content bookmark around the form.
  // @see Drupal.AjaxCommands.prototype.webformScrollTop
  $wrapper_id = $this
    ->getWrapperId();
  $wrapper_attributes = [];
  $wrapper_attributes['id'] = $wrapper_id;
  $wrapper_attributes['class'] = [
    'webform-ajax-form-wrapper',
  ];
  if (isset($settings['effect'])) {
    $wrapper_attributes['data-effect'] = $settings['effect'];
  }
  if (isset($settings['progress']['type'])) {
    $wrapper_attributes['data-progress-type'] = $settings['progress']['type'];
  }
  $wrapper_attributes = new Attribute($wrapper_attributes);
  $form['#form_wrapper_id'] = $wrapper_id;
  $form['#prefix'] = '<span id="' . $wrapper_id . '-content"></span>';
  $form['#prefix'] .= '<div' . $wrapper_attributes . '>';
  $form['#suffix'] = '</div>';

  // Add Ajax library which contains 'Scroll to top' Ajax command and
  // Ajax callback for confirmation back to link.
  $form['#attached']['library'][] = 'webform/webform.ajax';

  // Add validate Ajax form.
  $form['#validate'][] = '::validateAjaxForm';
  return $form;
}