Updated to Drupal 8.5. Core Media not yet in use.
[yaffs-website] / web / core / modules / layout_builder / src / Form / AjaxFormHelperTrait.php
diff --git a/web/core/modules/layout_builder/src/Form/AjaxFormHelperTrait.php b/web/core/modules/layout_builder/src/Form/AjaxFormHelperTrait.php
new file mode 100644 (file)
index 0000000..a5a3870
--- /dev/null
@@ -0,0 +1,61 @@
+<?php
+
+namespace Drupal\layout_builder\Form;
+
+use Drupal\Core\Ajax\AjaxResponse;
+use Drupal\Core\Ajax\ReplaceCommand;
+use Drupal\Core\Form\FormStateInterface;
+use Drupal\layout_builder\Controller\AjaxHelperTrait;
+
+/**
+ * Provides a helper to for submitting an AJAX form.
+ *
+ * @internal
+ *
+ * @todo Move to \Drupal\Core in https://www.drupal.org/node/2896535.
+ */
+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,
+      ];
+      $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.
+   */
+  abstract protected function successfulAjaxSubmit(array $form, FormStateInterface $form_state);
+
+}