You are here

public function ValidationTest::testCustomRequiredError in Drupal 8

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

Tests #required with custom validation errors.

See also

\Drupal\form_test\Form\FormTestValidateRequiredForm

File

core/modules/system/tests/src/Functional/Form/ValidationTest.php, line 213

Class

ValidationTest
Tests form processing and alteration via form validation handlers.

Namespace

Drupal\Tests\system\Functional\Form

Code

public function testCustomRequiredError() {
  $form = \Drupal::formBuilder()
    ->getForm('\\Drupal\\form_test\\Form\\FormTestValidateRequiredForm');

  // Verify that a custom #required error can be set.
  $edit = [];
  $this
    ->drupalPostForm('form-test/validate-required', $edit, 'Submit');
  foreach (Element::children($form) as $key) {
    if (isset($form[$key]['#required_error'])) {
      $this
        ->assertNoText(t('@name field is required.', [
        '@name' => $form[$key]['#title'],
      ]));
      $this
        ->assertText($form[$key]['#required_error']);
    }
    elseif (isset($form[$key]['#form_test_required_error'])) {
      $this
        ->assertNoText(t('@name field is required.', [
        '@name' => $form[$key]['#title'],
      ]));
      $this
        ->assertText($form[$key]['#form_test_required_error']);
    }
  }
  $this
    ->assertNoText(t('An illegal choice has been detected. Please contact the site administrator.'));

  // Verify that no custom validation error appears with valid values.
  $edit = [
    'textfield' => $this
      ->randomString(),
    'checkboxes[foo]' => TRUE,
    'select' => 'foo',
  ];
  $this
    ->drupalPostForm('form-test/validate-required', $edit, 'Submit');
  foreach (Element::children($form) as $key) {
    if (isset($form[$key]['#required_error'])) {
      $this
        ->assertNoText(t('@name field is required.', [
        '@name' => $form[$key]['#title'],
      ]));
      $this
        ->assertNoText($form[$key]['#required_error']);
    }
    elseif (isset($form[$key]['#form_test_required_error'])) {
      $this
        ->assertNoText(t('@name field is required.', [
        '@name' => $form[$key]['#title'],
      ]));
      $this
        ->assertNoText($form[$key]['#form_test_required_error']);
    }
  }
  $this
    ->assertNoText(t('An illegal choice has been detected. Please contact the site administrator.'));
}