3 namespace Drupal\layout_builder\Form;
5 use Drupal\Core\Ajax\AjaxResponse;
6 use Drupal\Core\Ajax\ReplaceCommand;
7 use Drupal\Core\Form\FormStateInterface;
8 use Drupal\layout_builder\Controller\AjaxHelperTrait;
11 * Provides a helper to for submitting an AJAX form.
15 * @todo Move to \Drupal\Core in https://www.drupal.org/node/2896535.
17 trait AjaxFormHelperTrait {
22 * Submit form dialog #ajax callback.
25 * An associative array containing the structure of the form.
26 * @param \Drupal\Core\Form\FormStateInterface $form_state
27 * The current state of the form.
29 * @return \Drupal\Core\Ajax\AjaxResponse
30 * An AJAX response that display validation error messages or represents a
31 * successful submission.
33 public function ajaxSubmit(array &$form, FormStateInterface $form_state) {
34 if ($form_state->hasAnyErrors()) {
35 $form['status_messages'] = [
36 '#type' => 'status_messages',
39 $response = new AjaxResponse();
40 $response->addCommand(new ReplaceCommand('[data-drupal-selector="' . $form['#attributes']['data-drupal-selector'] . '"]', $form));
43 $response = $this->successfulAjaxSubmit($form, $form_state);
49 * Allows the form to respond to a successful AJAX submission.
52 * An associative array containing the structure of the form.
53 * @param \Drupal\Core\Form\FormStateInterface $form_state
54 * The current state of the form.
56 * @return \Drupal\Core\Ajax\AjaxResponse
59 abstract protected function successfulAjaxSubmit(array $form, FormStateInterface $form_state);