AjaxFormHelperTrait.php

Same filename in other branches
  1. 9 core/lib/Drupal/Core/Ajax/AjaxFormHelperTrait.php
  2. 8.9.x core/lib/Drupal/Core/Ajax/AjaxFormHelperTrait.php
  3. 10 core/lib/Drupal/Core/Ajax/AjaxFormHelperTrait.php

Namespace

Drupal\Core\Ajax

File

core/lib/Drupal/Core/Ajax/AjaxFormHelperTrait.php

View source
<?php

namespace Drupal\Core\Ajax;

use Drupal\Core\Form\FormStateInterface;

/**
 * Provides a helper to for submitting an AJAX form.
 *
 * @internal
 */
trait AjaxFormHelperTrait {
    use AjaxHelperTrait;
    
    /**
     * Submit form dialog #ajax callback.
     *
     * @param array $form
     *   An associative array containing the structure of the form.
     * @param \Drupal\Core\Form\FormStateInterface $form_state
     *   The current state of the form.
     *
     * @return \Drupal\Core\Ajax\AjaxResponse
     *   An AJAX response that display validation error messages or represents a
     *   successful submission.
     */
    public function ajaxSubmit(array &$form, FormStateInterface $form_state) {
        if ($form_state->hasAnyErrors()) {
            $form['status_messages'] = [
                '#type' => 'status_messages',
                '#weight' => -1000,
            ];
            $form['#sorted'] = FALSE;
            $response = new AjaxResponse();
            $response->addCommand(new ReplaceCommand('[data-drupal-selector="' . $form['#attributes']['data-drupal-selector'] . '"]', $form));
        }
        else {
            $response = $this->successfulAjaxSubmit($form, $form_state);
        }
        return $response;
    }
    
    /**
     * Allows the form to respond to a successful AJAX submission.
     *
     * @param array $form
     *   An associative array containing the structure of the form.
     * @param \Drupal\Core\Form\FormStateInterface $form_state
     *   The current state of the form.
     *
     * @return \Drupal\Core\Ajax\AjaxResponse
     *   An AJAX response.
     */
    protected abstract function successfulAjaxSubmit(array $form, FormStateInterface $form_state);

}

Traits

Title Deprecated Summary
AjaxFormHelperTrait Provides a helper to for submitting an AJAX form.

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.