FormErrorHandler.php 5.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167
  1. <?php
  2. namespace Drupal\Core\Form;
  3. use Drupal\Component\Utility\NestedArray;
  4. use Drupal\Core\Messenger\MessengerTrait;
  5. use Drupal\Core\Render\Element;
  6. /**
  7. * Handles form errors.
  8. */
  9. class FormErrorHandler implements FormErrorHandlerInterface {
  10. use MessengerTrait;
  11. /**
  12. * {@inheritdoc}
  13. */
  14. public function handleFormErrors(array &$form, FormStateInterface $form_state) {
  15. // After validation check if there are errors.
  16. if ($errors = $form_state->getErrors()) {
  17. // Display error messages for each element.
  18. $this->displayErrorMessages($form, $form_state);
  19. // Loop through and assign each element its errors.
  20. $this->setElementErrorsFromFormState($form, $form_state);
  21. }
  22. return $this;
  23. }
  24. /**
  25. * Loops through and displays all form errors.
  26. *
  27. * @param array $form
  28. * An associative array containing the structure of the form.
  29. * @param \Drupal\Core\Form\FormStateInterface $form_state
  30. * The current state of the form.
  31. */
  32. protected function displayErrorMessages(array $form, FormStateInterface $form_state) {
  33. $errors = $form_state->getErrors();
  34. // Loop through all form errors and set an error message.
  35. foreach ($errors as $error) {
  36. $this->messenger()->addMessage($error, 'error');
  37. }
  38. }
  39. /**
  40. * Stores errors and a list of child element errors directly on each element.
  41. *
  42. * Grouping elements like containers, details, fieldgroups and fieldsets may
  43. * need error info from their child elements to be able to accessibly show
  44. * form error messages to a user. For example, a details element should be
  45. * opened when child elements have errors.
  46. *
  47. * Grouping example:
  48. * Assume you have a 'street' element somewhere in a form, which is displayed
  49. * in a details element 'address'. It might be:
  50. *
  51. * @code
  52. * $form['street'] = [
  53. * '#type' => 'textfield',
  54. * '#title' => $this->t('Street'),
  55. * '#group' => 'address',
  56. * '#required' => TRUE,
  57. * ];
  58. * $form['address'] = [
  59. * '#type' => 'details',
  60. * '#title' => $this->t('Address'),
  61. * ];
  62. * @endcode
  63. *
  64. * When submitting an empty street field, the generated error is available to
  65. * the different render elements like so:
  66. * @code
  67. * // The street textfield element.
  68. * $element = [
  69. * '#errors' => {Drupal\Core\StringTranslation\TranslatableMarkup},
  70. * '#children_errors' => [],
  71. * ];
  72. * // The address detail element.
  73. * $element = [
  74. * '#errors' => null,
  75. * '#children_errors' => [
  76. * 'street' => {Drupal\Core\StringTranslation\TranslatableMarkup}
  77. * ],
  78. * ];
  79. * @endcode
  80. *
  81. * The list of child element errors of an element is an associative array. A
  82. * child element error is keyed with the #array_parents value of the
  83. * respective element. The key is formed by imploding this value with '][' as
  84. * glue. For example, a value ['contact_info', 'name'] becomes
  85. * 'contact_info][name'.
  86. *
  87. * @param array $form
  88. * An associative array containing a reference to the complete structure of
  89. * the form.
  90. * @param \Drupal\Core\Form\FormStateInterface $form_state
  91. * The current state of the form.
  92. * @param array $elements
  93. * An associative array containing the part of the form structure that will
  94. * be processed while traversing up the tree. For recursion only; leave
  95. * empty when calling this method.
  96. */
  97. protected function setElementErrorsFromFormState(array &$form, FormStateInterface $form_state, array &$elements = []) {
  98. // At the start of traversing up the form tree set the to be processed
  99. // elements to the complete form structure by reference so that we can
  100. // modify the original form. When processing grouped elements a reference to
  101. // the complete form is needed.
  102. if (empty($elements)) {
  103. $elements = &$form;
  104. }
  105. // Recurse through all element children.
  106. foreach (Element::children($elements) as $key) {
  107. if (!empty($elements[$key])) {
  108. // Get the child by reference so that we can update the original form.
  109. $child = &$elements[$key];
  110. // Call self to traverse up the form tree. The current element's child
  111. // contains the next elements to be processed.
  112. $this->setElementErrorsFromFormState($form, $form_state, $child);
  113. $children_errors = [];
  114. // Inherit all recorded "children errors" of the direct child.
  115. if (!empty($child['#children_errors'])) {
  116. $children_errors = $child['#children_errors'];
  117. }
  118. // Additionally store the errors of the direct child itself, keyed by
  119. // its parent elements structure.
  120. if (!empty($child['#errors'])) {
  121. $child_parents = implode('][', $child['#array_parents']);
  122. $children_errors[$child_parents] = $child['#errors'];
  123. }
  124. if (!empty($elements['#children_errors'])) {
  125. $elements['#children_errors'] += $children_errors;
  126. }
  127. else {
  128. $elements['#children_errors'] = $children_errors;
  129. }
  130. // If this direct child belongs to a group populate the grouping element
  131. // with the children errors.
  132. if (!empty($child['#group'])) {
  133. $parents = explode('][', $child['#group']);
  134. $group_element = NestedArray::getValue($form, $parents);
  135. if (isset($group_element['#children_errors'])) {
  136. $group_element['#children_errors'] = $group_element['#children_errors'] + $children_errors;
  137. }
  138. else {
  139. $group_element['#children_errors'] = $children_errors;
  140. }
  141. NestedArray::setValue($form, $parents, $group_element);
  142. }
  143. }
  144. }
  145. // Store the errors for this element on the element directly.
  146. $elements['#errors'] = $form_state->getError($elements);
  147. }
  148. }