Verified Commit fdce680b authored by Alex Pott's avatar Alex Pott
Browse files

fix: #2980380 Inline error messages are not using proper theming mechanisms

By: jrockowitz
By: markhalliwell
By: pameeela
By: smustgrave
By: dcam
(cherry picked from commit bdba9f89)
parent 5e71310c
Loading
Loading
Loading
Loading
Loading
+5 −11
Changes for core/modules/inline_form_errors/src/FormErrorHandler.php: 5 added lines, 11 removed lines.
Original line number Diff line number Diff line
@@ -96,7 +96,7 @@ protected function displayErrorMessages(array $form, FormStateInterface $form_st
      }
      elseif ($is_visible_element && $has_title && $has_id) {
        $url = Url::fromRoute('<none>', [], ['fragment' => $form_element['#id'], 'external' => TRUE]);
        $error_links[] = Link::fromTextAndUrl($title, $url)->toRenderable();
        $error_links[] = ['value' => Link::fromTextAndUrl($title, $url)->toRenderable()];
        unset($errors[$name]);
      }
    }
@@ -108,17 +108,11 @@ protected function displayErrorMessages(array $form, FormStateInterface $form_st

    if (!empty($error_links)) {
      $render_array = [
        [
          '#markup' => $this->formatPlural(count($error_links), '1 error has been found: ', '@count errors have been found: '),
        ],
        [
          '#theme' => 'item_list',
          '#items' => $error_links,
          '#context' => ['list_style' => 'comma-list'],
        ],
        '#theme' => 'inline_form_errors_summary',
        '#error_links' => $error_links,
        '#form_id' => $form['#form_id'] ?? NULL,
      ];
      $message = $this->renderer->renderInIsolation($render_array);
      $this->messenger->addError($message);
      $this->messenger->addError($this->renderer->renderInIsolation($render_array));
    }
  }

+25 −1
Changes for core/modules/inline_form_errors/src/Hook/InlineFormErrorsThemeHooks.php: 25 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -8,9 +8,33 @@
 * Hook implementations for inline_form_errors.
 */
class InlineFormErrorsThemeHooks {

  /**
   * @file
   * Implements hook_theme().
   */
  #[Hook('theme')]
  public function theme(): array {
    return [
      'inline_form_errors_summary' => [
        'variables' => [
          'error_links' => [],
          'form_id' => NULL,
        ],
      ],
    ];
  }

  /**
   * Implements hook_theme_suggestions_HOOK().
   */
  #[Hook('theme_suggestions_inline_form_errors_summary')]
  public function themeSuggestionsInlineFormErrorsSummary(array $variables): array {
    $suggestions = [];
    if (!empty($variables['form_id'])) {
      $suggestions[] = 'inline_form_errors_summary__' . $variables['form_id'];
    }
    return $suggestions;
  }

  /**
   * Implements hook_preprocess_HOOK() for form element templates.
+28
Changes for core/modules/inline_form_errors/templates/inline-form-errors-summary.html.twig: 28 added lines, 0 removed lines.
Original line number Diff line number Diff line
{#
/**
 * @file
 * Default theme implementation for the Inline Form Errors summary.
 *
 * Available variables:
 * - error_links: A list of render arrays for the errored elements, one link
 *   per element.
 * - form_id: The form's machine ID; drives the theme suggestion
 *   inline_form_errors_summary__FORM_ID.
 *
 * @ingroup themeable
 */
#}
{% if error_links %}
  {%- set count = error_links|length -%}
  {%- trans -%}
    <span>{{ count }} error has been found:</span>
  {%- plural count -%}
    <span>{{ count }} errors have been found:</span>
  {%- endtrans -%}
  {{ include('item-list.html.twig', {
    items: error_links,
    list_type: 'ul',
    wrapper_attributes: create_attribute(),
    context: {list_style: 'comma-list'},
  }) }}
{% endif %}
+25 −5
Changes for core/modules/inline_form_errors/tests/src/Unit/FormErrorHandlerTest.php: 25 added lines, 5 removed lines.
Original line number Diff line number Diff line
@@ -119,7 +119,7 @@ public function testErrorMessagesInline(): void {
      'no title given',
      'element is invisible',
      'this missing element is invalid',
      '3 errors have been found: <ul-comma-list-mock><li-mock>Test 1</li-mock><li-mock>Test 2 &amp; a half</li-mock><li-mock>Test 3</li-mock></ul-comma-list-mock>',
      '<ul-comma-list-mock><li-mock>Test 1</li-mock><li-mock>Test 2 &amp; a half</li-mock><li-mock>Test 3</li-mock></ul-comma-list-mock>',
    ];

    $this->messenger->expects($this->exactly(count($messages)))
@@ -135,11 +135,10 @@ public function testErrorMessagesInline(): void {
      ->method('renderInIsolation')
      ->willReturnCallback(function ($render_array): string {
        $links = [];
        foreach ($render_array[1]['#items'] as $item) {
          $links[] = htmlspecialchars($item['#title']);
        foreach ($render_array['#error_links'] as $item) {
          $links[] = htmlspecialchars($item['value']['#title']);
        }

        return $render_array[0]['#markup'] . '<ul-comma-list-mock><li-mock>' . implode('</li-mock><li-mock>', $links) . '</li-mock></ul-comma-list-mock>';
        return '<ul-comma-list-mock><li-mock>' . implode('</li-mock><li-mock>', $links) . '</li-mock></ul-comma-list-mock>';
      });

    $form_state = new FormState();
@@ -161,6 +160,27 @@ public function testErrorMessagesInline(): void {
    $this->assertSame('element is invisible', $this->testForm['test6']['#errors']);
  }

  /**
   * Tests that the summary render array exposes error_links and form_id.
   */
  public function testSummaryRenderArrayVariables(): void {
    $this->messenger->expects($this->atLeastOnce())->method('addError');

    $this->renderer->expects($this->once())
      ->method('renderInIsolation')
      ->with($this->callback(function ($render_array): bool {
        $this->assertSame('inline_form_errors_summary', $render_array['#theme']);
        $this->assertSame('test_form', $render_array['#form_id']);
        $this->assertCount(1, $render_array['#error_links']);
        return TRUE;
      }))
      ->willReturn('hello');

    $form_state = new FormState();
    $form_state->setErrorByName('test1', 'invalid');
    $this->formErrorHandler->handleFormErrors($this->testForm, $form_state);
  }

  /**
   * Tests that opting out of Inline Form Errors works.
   */
+2 −1
Changes for core/modules/path/tests/src/Functional/PathAliasTest.php: 2 added lines, 1 removed line.
Original line number Diff line number Diff line
@@ -421,7 +421,8 @@ public function testDuplicateNodeAlias(): void {
    // This error should still be present next to the field.
    $this->assertSession()->pageTextContains("The alias {$edit['path[0][alias]']} is already in use in this language.");
    // The validation error set for the page should include this text.
    $this->assertSession()->statusMessageContains('1 error has been found: URL alias', 'error');
    $this->assertSession()->statusMessageContains('1 error has been found:', 'error');
    $this->assertSession()->statusMessageContains('URL alias', 'error');
    // The text 'URL alias' should be a link.
    $this->assertSession()->linkExists('URL alias');
    // The link should be to the ID of the URL alias field.