You are here

public function FormTest::testDisabledMarkup in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/system/tests/src/Functional/Form/FormTest.php \Drupal\Tests\system\Functional\Form\FormTest::testDisabledMarkup()

Verify markup for disabled form elements.

See also

_form_test_disabled_elements()

File

core/modules/system/tests/src/Functional/Form/FormTest.php, line 821

Class

FormTest
Tests various form element validation mechanisms.

Namespace

Drupal\Tests\system\Functional\Form

Code

public function testDisabledMarkup() {
  $this
    ->drupalGet('form-test/disabled-elements');
  $form = \Drupal::formBuilder()
    ->getForm('\\Drupal\\form_test\\Form\\FormTestDisabledElementsForm');
  $type_map = [
    'textarea' => 'textarea',
    'select' => 'select',
    'weight' => 'select',
    'datetime' => 'datetime',
  ];
  foreach ($form as $name => $item) {

    // Skip special #types.
    if (!isset($item['#type']) || in_array($item['#type'], [
      'hidden',
      'text_format',
    ])) {
      continue;
    }

    // Setup XPath and CSS class depending on #type.
    if (in_array($item['#type'], [
      'button',
      'submit',
    ])) {
      $path = "//!type[contains(@class, :div-class) and @value=:value]";
      $class = 'is-disabled';
    }
    elseif (in_array($item['#type'], [
      'image_button',
    ])) {
      $path = "//!type[contains(@class, :div-class) and @value=:value]";
      $class = 'is-disabled';
    }
    else {

      // starts-with() required for checkboxes.
      $path = "//div[contains(@class, :div-class)]/descendant::!type[starts-with(@name, :name)]";
      $class = 'form-disabled';
    }

    // Replace DOM element name in $path according to #type.
    $type = 'input';
    if (isset($type_map[$item['#type']])) {
      $type = $type_map[$item['#type']];
    }
    if (isset($item['#value']) && is_object($item['#value'])) {
      $item['#value'] = (string) $item['#value'];
    }
    $path = strtr($path, [
      '!type' => $type,
    ]);

    // Verify that the element exists.
    $element = $this
      ->xpath($path, [
      ':name' => Html::escape($name),
      ':div-class' => $class,
      ':value' => isset($item['#value']) ? $item['#value'] : '',
    ]);
    $this
      ->assertTrue(isset($element[0]), new FormattableMarkup('Disabled form element class found for #type %type.', [
      '%type' => $item['#type'],
    ]));
  }

  // Verify special element #type text-format.
  $this
    ->assertSession()
    ->elementExists('xpath', "//div[contains(@class, 'form-disabled')]/descendant::textarea[@name='text_format[value]']");
  $this
    ->assertSession()
    ->elementExists('xpath', "//div[contains(@class, 'form-disabled')]/descendant::select[@name='text_format[format]']");
}