a5a387020f9d6c383295ca037a4da8380f1d05e3
[yaffs-website] / web / core / modules / layout_builder / src / Form / AjaxFormHelperTrait.php
1 <?php
2
3 namespace Drupal\layout_builder\Form;
4
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;
9
10 /**
11  * Provides a helper to for submitting an AJAX form.
12  *
13  * @internal
14  *
15  * @todo Move to \Drupal\Core in https://www.drupal.org/node/2896535.
16  */
17 trait AjaxFormHelperTrait {
18
19   use AjaxHelperTrait;
20
21   /**
22    * Submit form dialog #ajax callback.
23    *
24    * @param array $form
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.
28    *
29    * @return \Drupal\Core\Ajax\AjaxResponse
30    *   An AJAX response that display validation error messages or represents a
31    *   successful submission.
32    */
33   public function ajaxSubmit(array &$form, FormStateInterface $form_state) {
34     if ($form_state->hasAnyErrors()) {
35       $form['status_messages'] = [
36         '#type' => 'status_messages',
37         '#weight' => -1000,
38       ];
39       $response = new AjaxResponse();
40       $response->addCommand(new ReplaceCommand('[data-drupal-selector="' . $form['#attributes']['data-drupal-selector'] . '"]', $form));
41     }
42     else {
43       $response = $this->successfulAjaxSubmit($form, $form_state);
44     }
45     return $response;
46   }
47
48   /**
49    * Allows the form to respond to a successful AJAX submission.
50    *
51    * @param array $form
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.
55    *
56    * @return \Drupal\Core\Ajax\AjaxResponse
57    *   An AJAX response.
58    */
59   abstract protected function successfulAjaxSubmit(array $form, FormStateInterface $form_state);
60
61 }