AjaxFormHelperTrait.php 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. <?php
  2. namespace Drupal\Core\Ajax;
  3. use Drupal\Core\Form\FormStateInterface;
  4. /**
  5. * Provides a helper to for submitting an AJAX form.
  6. *
  7. * @internal
  8. */
  9. trait AjaxFormHelperTrait {
  10. use AjaxHelperTrait;
  11. /**
  12. * Submit form dialog #ajax callback.
  13. *
  14. * @param array $form
  15. * An associative array containing the structure of the form.
  16. * @param \Drupal\Core\Form\FormStateInterface $form_state
  17. * The current state of the form.
  18. *
  19. * @return \Drupal\Core\Ajax\AjaxResponse
  20. * An AJAX response that display validation error messages or represents a
  21. * successful submission.
  22. */
  23. public function ajaxSubmit(array &$form, FormStateInterface $form_state) {
  24. if ($form_state->hasAnyErrors()) {
  25. $form['status_messages'] = [
  26. '#type' => 'status_messages',
  27. '#weight' => -1000,
  28. ];
  29. $form['#sorted'] = FALSE;
  30. $response = new AjaxResponse();
  31. $response->addCommand(new ReplaceCommand('[data-drupal-selector="' . $form['#attributes']['data-drupal-selector'] . '"]', $form));
  32. }
  33. else {
  34. $response = $this->successfulAjaxSubmit($form, $form_state);
  35. }
  36. return $response;
  37. }
  38. /**
  39. * Allows the form to respond to a successful AJAX submission.
  40. *
  41. * @param array $form
  42. * An associative array containing the structure of the form.
  43. * @param \Drupal\Core\Form\FormStateInterface $form_state
  44. * The current state of the form.
  45. *
  46. * @return \Drupal\Core\Ajax\AjaxResponse
  47. * An AJAX response.
  48. */
  49. abstract protected function successfulAjaxSubmit(array $form, FormStateInterface $form_state);
  50. }