3 namespace Drupal\Tests\system\Functional\Form;
5 use Drupal\Component\Serialization\Json;
6 use Drupal\Component\Utility\Html;
7 use Drupal\Component\Utility\SafeMarkup;
8 use Drupal\Core\Form\FormState;
9 use Drupal\Core\Render\Element;
11 use Drupal\form_test\Form\FormTestDisabledElementsForm;
12 use Drupal\Tests\BrowserTestBase;
13 use Drupal\user\RoleInterface;
14 use Drupal\filter\Entity\FilterFormat;
17 * Tests various form element validation mechanisms.
21 class FormTest extends BrowserTestBase {
28 public static $modules = ['filter', 'form_test', 'file', 'datetime'];
30 protected function setUp() {
33 $filtered_html_format = FilterFormat::create([
34 'format' => 'filtered_html',
35 'name' => 'Filtered HTML',
37 $filtered_html_format->save();
39 $filtered_html_permission = $filtered_html_format->getPermissionName();
40 user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, [$filtered_html_permission]);
44 * Check several empty values for required forms elements.
46 * Carriage returns, tabs, spaces, and unchecked checkbox elements are not
47 * valid content for a required field.
49 * If the form field is found in $form_state->getErrors() then the test pass.
51 public function testRequiredFields() {
52 // Originates from https://www.drupal.org/node/117748.
53 // Sets of empty strings and arrays.
54 $empty_strings = ['""' => "", '"\n"' => "\n", '" "' => " ", '"\t"' => "\t", '" \n\t "' => " \n\t ", '"\n\n\n\n\n"' => "\n\n\n\n\n"];
55 $empty_arrays = ['array()' => []];
56 $empty_checkbox = [NULL];
58 $elements['textfield']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'textfield'];
59 $elements['textfield']['empty_values'] = $empty_strings;
61 $elements['telephone']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'tel'];
62 $elements['telephone']['empty_values'] = $empty_strings;
64 $elements['url']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'url'];
65 $elements['url']['empty_values'] = $empty_strings;
67 $elements['search']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'search'];
68 $elements['search']['empty_values'] = $empty_strings;
70 $elements['password']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'password'];
71 $elements['password']['empty_values'] = $empty_strings;
73 $elements['password_confirm']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'password_confirm'];
74 // Provide empty values for both password fields.
75 foreach ($empty_strings as $key => $value) {
76 $elements['password_confirm']['empty_values'][$key] = ['pass1' => $value, 'pass2' => $value];
79 $elements['textarea']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'textarea'];
80 $elements['textarea']['empty_values'] = $empty_strings;
82 $elements['radios']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'radios', '#options' => ['' => t('None'), $this->randomMachineName(), $this->randomMachineName(), $this->randomMachineName()]];
83 $elements['radios']['empty_values'] = $empty_arrays;
85 $elements['checkbox']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'checkbox', '#required' => TRUE];
86 $elements['checkbox']['empty_values'] = $empty_checkbox;
88 $elements['checkboxes']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'checkboxes', '#options' => [$this->randomMachineName(), $this->randomMachineName(), $this->randomMachineName()]];
89 $elements['checkboxes']['empty_values'] = $empty_arrays;
91 $elements['select']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'select', '#options' => ['' => t('None'), $this->randomMachineName(), $this->randomMachineName(), $this->randomMachineName()]];
92 $elements['select']['empty_values'] = $empty_strings;
94 $elements['file']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'file'];
95 $elements['file']['empty_values'] = $empty_strings;
97 // Regular expression to find the expected marker on required elements.
98 $required_marker_preg = '@<.*?class=".*?js-form-required.*form-required.*?">@';
99 // Go through all the elements and all the empty values for them.
100 foreach ($elements as $type => $data) {
101 foreach ($data['empty_values'] as $key => $empty) {
102 foreach ([TRUE, FALSE] as $required) {
103 $form_id = $this->randomMachineName();
105 $form_state = new FormState();
106 $form['op'] = ['#type' => 'submit', '#value' => t('Submit')];
107 $element = $data['element']['#title'];
108 $form[$element] = $data['element'];
109 $form[$element]['#required'] = $required;
110 $user_input[$element] = $empty;
111 $user_input['form_id'] = $form_id;
112 $form_state->setUserInput($user_input);
113 $form_state->setFormObject(new StubForm($form_id, $form));
114 $form_state->setMethod('POST');
115 // The form token CSRF protection should not interfere with this test,
116 // so we bypass it by setting the token to FALSE.
117 $form['#token'] = FALSE;
118 \Drupal::formBuilder()->prepareForm($form_id, $form, $form_state);
119 \Drupal::formBuilder()->processForm($form_id, $form, $form_state);
120 $errors = $form_state->getErrors();
121 // Form elements of type 'radios' throw all sorts of PHP notices
122 // when you try to render them like this, so we ignore those for
123 // testing the required marker.
124 // @todo Fix this work-around (https://www.drupal.org/node/588438).
125 $form_output = ($type == 'radios') ? '' : \Drupal::service('renderer')->renderRoot($form);
127 // Make sure we have a form error for this element.
128 $this->assertTrue(isset($errors[$element]), "Check empty($key) '$type' field '$element'");
129 if (!empty($form_output)) {
130 // Make sure the form element is marked as required.
131 $this->assertTrue(preg_match($required_marker_preg, $form_output), "Required '$type' field is marked as required");
135 if (!empty($form_output)) {
136 // Make sure the form element is *not* marked as required.
137 $this->assertFalse(preg_match($required_marker_preg, $form_output), "Optional '$type' field is not marked as required");
139 if ($type == 'select') {
140 // Select elements are going to have validation errors with empty
141 // input, since those are illegal choices. Just make sure the
142 // error is not "field is required".
143 $this->assertTrue((empty($errors[$element]) || strpos('field is required', (string) $errors[$element]) === FALSE), "Optional '$type' field '$element' is not treated as a required element");
146 // Make sure there is *no* form error for this element.
147 $this->assertTrue(empty($errors[$element]), "Optional '$type' field '$element' has no errors with empty input");
153 // Clear the expected form error messages so they don't appear as exceptions.
154 drupal_get_messages();
158 * Tests validation for required checkbox, select, and radio elements.
160 * Submits a test form containing several types of form elements. The form
161 * is submitted twice, first without values for required fields and then
162 * with values. Each submission is checked for relevant error messages.
164 * @see \Drupal\form_test\Form\FormTestValidateRequiredForm
166 public function testRequiredCheckboxesRadio() {
167 $form = \Drupal::formBuilder()->getForm('\Drupal\form_test\Form\FormTestValidateRequiredForm');
169 // Attempt to submit the form with no required fields set.
171 $this->drupalPostForm('form-test/validate-required', $edit, 'Submit');
173 // The only error messages that should appear are the relevant 'required'
174 // messages for each field.
176 foreach (['textfield', 'checkboxes', 'select', 'radios'] as $key) {
177 if (isset($form[$key]['#required_error'])) {
178 $expected[] = $form[$key]['#required_error'];
180 elseif (isset($form[$key]['#form_test_required_error'])) {
181 $expected[] = $form[$key]['#form_test_required_error'];
184 $expected[] = t('@name field is required.', ['@name' => $form[$key]['#title']]);
188 // Check the page for error messages.
189 $errors = $this->xpath('//div[contains(@class, "error")]//li');
190 foreach ($errors as $error) {
191 $expected_key = array_search($error->getText(), $expected);
192 // If the error message is not one of the expected messages, fail.
193 if ($expected_key === FALSE) {
194 $this->fail(format_string("Unexpected error message: @error", ['@error' => $error[0]]));
196 // Remove the expected message from the list once it is found.
198 unset($expected[$expected_key]);
202 // Fail if any expected messages were not found.
203 foreach ($expected as $not_found) {
204 $this->fail(format_string("Found error message: @error", ['@error' => $not_found]));
207 // Verify that input elements are still empty.
208 $this->assertFieldByName('textfield', '');
209 $this->assertNoFieldChecked('edit-checkboxes-foo');
210 $this->assertNoFieldChecked('edit-checkboxes-bar');
211 $this->assertOptionSelected('edit-select', '');
212 $this->assertNoFieldChecked('edit-radios-foo');
213 $this->assertNoFieldChecked('edit-radios-bar');
214 $this->assertNoFieldChecked('edit-radios-optional-foo');
215 $this->assertNoFieldChecked('edit-radios-optional-bar');
216 $this->assertNoFieldChecked('edit-radios-optional-default-value-false-foo');
217 $this->assertNoFieldChecked('edit-radios-optional-default-value-false-bar');
219 // Submit again with required fields set and verify that there are no
222 'textfield' => $this->randomString(),
223 'checkboxes[foo]' => TRUE,
227 $this->drupalPostForm(NULL, $edit, 'Submit');
228 $this->assertNoFieldByXpath('//div[contains(@class, "error")]', FALSE, 'No error message is displayed when all required fields are filled.');
229 $this->assertRaw("The form_test_validate_required_form form was submitted successfully.", 'Validation form submitted successfully.');
233 * Tests that input is retained for safe elements even with an invalid token.
235 * Submits a test form containing several types of form elements.
237 public function testInputWithInvalidToken() {
238 // We need to be logged in to have CSRF tokens.
239 $account = $this->createUser();
240 $this->drupalLogin($account);
241 // Submit again with required fields set but an invalid form token and
242 // verify that all the values are retained.
243 $this->drupalGet(Url::fromRoute('form_test.validate_required'));
244 $this->assertSession()
245 ->elementExists('css', 'input[name="form_token"]')
246 ->setValue('invalid token');
248 'textfield' => $this->randomString(),
249 'checkboxes[bar]' => TRUE,
253 $this->drupalPostForm(NULL, $edit, 'Submit');
254 $this->assertFieldByXpath('//div[contains(@class, "error")]', NULL, 'Error message is displayed with invalid token even when required fields are filled.');
255 $this->assertText('The form has become outdated. Copy any unsaved work in the form below');
256 // Verify that input elements retained the posted values.
257 $this->assertFieldByName('textfield', $edit['textfield']);
258 $this->assertNoFieldChecked('edit-checkboxes-foo');
259 $this->assertFieldChecked('edit-checkboxes-bar');
260 $this->assertOptionSelected('edit-select', 'bar');
261 $this->assertFieldChecked('edit-radios-foo');
263 // Check another form that has a textarea input.
264 $this->drupalGet(Url::fromRoute('form_test.required'));
265 $this->assertSession()
266 ->elementExists('css', 'input[name="form_token"]')
267 ->setValue('invalid token');
269 'textfield' => $this->randomString(),
270 'textarea' => $this->randomString() . "\n",
272 $this->drupalPostForm(NULL, $edit, 'Submit');
273 $this->assertFieldByXpath('//div[contains(@class, "error")]', NULL, 'Error message is displayed with invalid token even when required fields are filled.');
274 $this->assertText('The form has become outdated. Copy any unsaved work in the form below');
275 $this->assertFieldByName('textfield', $edit['textfield']);
276 $this->assertFieldByName('textarea', $edit['textarea']);
278 // Check another form that has a number input.
279 $this->drupalGet(Url::fromRoute('form_test.number'));
280 $this->assertSession()
281 ->elementExists('css', 'input[name="form_token"]')
282 ->setValue('invalid token');
284 'integer_step' => mt_rand(1, 100),
286 $this->drupalPostForm(NULL, $edit, 'Submit');
287 $this->assertFieldByXpath('//div[contains(@class, "error")]', NULL, 'Error message is displayed with invalid token even when required fields are filled.');
288 $this->assertText('The form has become outdated. Copy any unsaved work in the form below');
289 $this->assertFieldByName('integer_step', $edit['integer_step']);
291 // Check a form with a Url field
292 $this->drupalGet(Url::fromRoute('form_test.url'));
293 $this->assertSession()
294 ->elementExists('css', 'input[name="form_token"]')
295 ->setValue('invalid token');
297 'url' => $this->randomString(),
299 $this->drupalPostForm(NULL, $edit, 'Submit');
300 $this->assertFieldByXpath('//div[contains(@class, "error")]', NULL, 'Error message is displayed with invalid token even when required fields are filled.');
301 $this->assertText('The form has become outdated. Copy any unsaved work in the form below');
302 $this->assertFieldByName('url', $edit['url']);
306 * CSRF tokens for GET forms should not be added by default.
308 public function testGetFormsCsrfToken() {
309 // We need to be logged in to have CSRF tokens.
310 $account = $this->createUser();
311 $this->drupalLogin($account);
313 $this->drupalGet(Url::fromRoute('form_test.get_form'));
314 $this->assertNoRaw('form_token');
318 * Tests validation for required textfield element without title.
320 * Submits a test form containing a textfield form element without title.
321 * The form is submitted twice, first without value for the required field
322 * and then with value. Each submission is checked for relevant error
325 * @see \Drupal\form_test\Form\FormTestValidateRequiredNoTitleForm
327 public function testRequiredTextfieldNoTitle() {
328 // Attempt to submit the form with no required field set.
330 $this->drupalPostForm('form-test/validate-required-no-title', $edit, 'Submit');
331 $this->assertNoRaw("The form_test_validate_required_form_no_title form was submitted successfully.", 'Validation form submitted successfully.');
333 // Check the page for the error class on the textfield.
334 $this->assertFieldByXPath('//input[contains(@class, "error")]', FALSE, 'Error input form element class found.');
336 // Check the page for the aria-invalid attribute on the textfield.
337 $this->assertFieldByXPath('//input[contains(@aria-invalid, "true")]', FALSE, 'Aria invalid attribute found.');
339 // Submit again with required fields set and verify that there are no
342 'textfield' => $this->randomString(),
344 $this->drupalPostForm(NULL, $edit, 'Submit');
345 $this->assertNoFieldByXpath('//input[contains(@class, "error")]', FALSE, 'No error input form element class found.');
346 $this->assertRaw("The form_test_validate_required_form_no_title form was submitted successfully.", 'Validation form submitted successfully.');
350 * Test default value handling for checkboxes.
352 * @see _form_test_checkbox()
354 public function testCheckboxProcessing() {
355 // First, try to submit without the required checkbox.
357 $this->drupalPostForm('form-test/checkbox', $edit, t('Submit'));
358 $this->assertRaw(t('@name field is required.', ['@name' => 'required_checkbox']), 'A required checkbox is actually mandatory');
360 // Now try to submit the form correctly.
361 $this->drupalPostForm(NULL, ['required_checkbox' => 1], t('Submit'));
362 $values = Json::decode($this->getSession()->getPage()->getContent());
364 'disabled_checkbox_on' => 'disabled_checkbox_on',
365 'disabled_checkbox_off' => 0,
366 'checkbox_on' => 'checkbox_on',
368 'zero_checkbox_on' => '0',
369 'zero_checkbox_off' => 0,
371 foreach ($expected_values as $widget => $expected_value) {
372 $this->assertSame($values[$widget], $expected_value, format_string('Checkbox %widget returns expected value (expected: %expected, got: %value)', [
373 '%widget' => var_export($widget, TRUE),
374 '%expected' => var_export($expected_value, TRUE),
375 '%value' => var_export($values[$widget], TRUE),
381 * Tests validation of #type 'select' elements.
383 public function testSelect() {
384 $form = \Drupal::formBuilder()->getForm('Drupal\form_test\Form\FormTestSelectForm');
385 $this->drupalGet('form-test/select');
387 // Verify that the options are escaped as expected.
388 $this->assertEscaped('<strong>four</strong>');
389 $this->assertNoRaw('<strong>four</strong>');
391 // Posting without any values should throw validation errors.
392 $this->drupalPostForm(NULL, [], 'Submit');
399 'no_default_optional',
400 'no_default_empty_option_optional',
401 'no_default_empty_value_optional',
403 'multiple_no_default',
405 foreach ($no_errors as $key) {
406 $this->assertNoText(t('@name field is required.', ['@name' => $form[$key]['#title']]));
411 'no_default_empty_option',
412 'no_default_empty_value',
413 'no_default_empty_value_one',
414 'multiple_no_default_required',
416 foreach ($expected_errors as $key) {
417 $this->assertText(t('@name field is required.', ['@name' => $form[$key]['#title']]));
420 // Post values for required fields.
422 'no_default' => 'three',
423 'no_default_empty_option' => 'three',
424 'no_default_empty_value' => 'three',
425 'no_default_empty_value_one' => 'three',
426 'multiple_no_default_required[]' => 'three',
428 $this->drupalPostForm(NULL, $edit, 'Submit');
429 $values = Json::decode($this->getRawContent());
431 // Verify expected values.
434 'empty_value' => 'one',
435 'empty_value_one' => 'one',
436 'no_default' => 'three',
437 'no_default_optional' => 'one',
438 'no_default_optional_empty_value' => '',
439 'no_default_empty_option' => 'three',
440 'no_default_empty_option_optional' => '',
441 'no_default_empty_value' => 'three',
442 'no_default_empty_value_one' => 'three',
443 'no_default_empty_value_optional' => 0,
444 'multiple' => ['two' => 'two'],
445 'multiple_no_default' => [],
446 'multiple_no_default_required' => ['three' => 'three'],
448 foreach ($expected as $key => $value) {
449 $this->assertIdentical($values[$key], $value, format_string('@name: @actual is equal to @expected.', [
451 '@actual' => var_export($values[$key], TRUE),
452 '@expected' => var_export($value, TRUE),
458 * Tests a select element when #options is not set.
460 public function testEmptySelect() {
461 $this->drupalGet('form-test/empty-select');
462 $this->assertFieldByXPath("//select[1]", NULL, 'Select element found.');
463 $this->assertNoFieldByXPath("//select[1]/option", NULL, 'No option element found.');
467 * Tests validation of #type 'number' and 'range' elements.
469 public function testNumber() {
470 $form = \Drupal::formBuilder()->getForm('\Drupal\form_test\Form\FormTestNumberForm');
472 // Array with all the error messages to be checked.
474 'no_number' => '%name must be a number.',
475 'too_low' => '%name must be higher than or equal to %min.',
476 'too_high' => '%name must be lower than or equal to %max.',
477 'step_mismatch' => '%name is not a valid number.',
480 // The expected errors.
482 'integer_no_number' => 'no_number',
483 'integer_no_step' => 0,
484 'integer_no_step_step_error' => 'step_mismatch',
486 'integer_step_error' => 'step_mismatch',
487 'integer_step_min' => 0,
488 'integer_step_min_error' => 'too_low',
489 'integer_step_max' => 0,
490 'integer_step_max_error' => 'too_high',
491 'integer_step_min_border' => 0,
492 'integer_step_max_border' => 0,
493 'integer_step_based_on_min' => 0,
494 'integer_step_based_on_min_error' => 'step_mismatch',
495 'float_small_step' => 0,
496 'float_step_no_error' => 0,
497 'float_step_error' => 'step_mismatch',
498 'float_step_hard_no_error' => 0,
499 'float_step_hard_error' => 'step_mismatch',
500 'float_step_any_no_error' => 0,
503 // First test the number element type, then range.
504 foreach (['form-test/number', 'form-test/number/range'] as $path) {
505 // Post form and show errors.
506 $this->drupalPostForm($path, [], 'Submit');
508 foreach ($expected as $element => $error) {
509 // Create placeholder array.
511 '%name' => $form[$element]['#title'],
512 '%min' => isset($form[$element]['#min']) ? $form[$element]['#min'] : '0',
513 '%max' => isset($form[$element]['#max']) ? $form[$element]['#max'] : '0',
516 foreach ($error_messages as $id => $message) {
517 // Check if the error exists on the page, if the current message ID is
518 // expected. Otherwise ensure that the error message is not present.
519 if ($id === $error) {
520 $this->assertRaw(format_string($message, $placeholders));
523 $this->assertNoRaw(format_string($message, $placeholders));
531 * Tests default value handling of #type 'range' elements.
533 public function testRange() {
534 $this->drupalPostForm('form-test/range', [], 'Submit');
535 $values = json_decode($this->getSession()->getPage()->getContent());
536 $this->assertEqual($values->with_default_value, 18);
537 $this->assertEqual($values->float, 10.5);
538 $this->assertEqual($values->integer, 6);
539 $this->assertEqual($values->offset, 6.9);
541 $this->drupalPostForm('form-test/range/invalid', [], 'Submit');
542 $this->assertFieldByXPath('//input[@type="range" and contains(@class, "error")]', NULL, 'Range element has the error class.');
546 * Tests validation of #type 'color' elements.
548 public function testColorValidation() {
549 // Keys are inputs, values are expected results.
554 '#af0DEE' => '#af0dee',
555 '#99ccBc' => '#99ccbc',
556 '#aabbcc' => '#aabbcc',
557 '123456' => '#123456',
560 // Tests that valid values are properly normalized.
561 foreach ($values as $input => $expected) {
565 $this->drupalPostForm('form-test/color', $edit, 'Submit');
566 $result = json_decode($this->getSession()->getPage()->getContent());
567 $this->assertEqual($result->color, $expected);
570 // Tests invalid values are rejected.
571 $values = ['#0008', '#1234', '#fffffg', '#abcdef22', '17', '#uaa'];
572 foreach ($values as $input) {
576 $this->drupalPostForm('form-test/color', $edit, 'Submit');
577 $this->assertRaw(t('%name must be a valid color.', ['%name' => 'Color']));
582 * Test handling of disabled elements.
584 * @see _form_test_disabled_elements()
586 public function testDisabledElements() {
587 // Get the raw form in its original state.
588 $form_state = new FormState();
589 $form = (new FormTestDisabledElementsForm())->buildForm([], $form_state);
591 // Build a submission that tries to hijack the form by submitting input for
592 // elements that are disabled.
594 foreach (Element::children($form) as $key) {
595 if (isset($form[$key]['#test_hijack_value'])) {
596 if (is_array($form[$key]['#test_hijack_value'])) {
597 foreach ($form[$key]['#test_hijack_value'] as $subkey => $value) {
598 $edit[$key . '[' . $subkey . ']'] = $value;
602 $edit[$key] = $form[$key]['#test_hijack_value'];
607 // Submit the form with no input, as the browser does for disabled elements,
608 // and fetch the $form_state->getValues() that is passed to the submit handler.
609 $this->drupalPostForm('form-test/disabled-elements', [], t('Submit'));
610 $returned_values['normal'] = Json::decode($this->getSession()->getPage()->getContent());
612 // Do the same with input, as could happen if JavaScript un-disables an
613 // element. drupalPostForm() emulates a browser by not submitting input for
614 // disabled elements, so we need to un-disable those elements first.
615 $this->drupalGet('form-test/disabled-elements');
616 $disabled_elements = [];
617 foreach ($this->xpath('//*[@disabled]') as $element) {
618 $disabled_elements[] = (string) $element->getAttribute('name');
621 // All the elements should be marked as disabled, including the ones below
622 // the disabled container.
623 $actual_count = count($disabled_elements);
624 $expected_count = 42;
625 $this->assertEqual($actual_count, $expected_count, SafeMarkup::format('Found @actual elements with disabled property (expected @expected).', [
626 '@actual' => count($disabled_elements),
627 '@expected' => $expected_count,
630 // Mink does not "see" hidden elements, so we need to set the value of the
631 // hidden element directly.
632 $this->assertSession()
633 ->elementExists('css', 'input[name="hidden"]')
634 ->setValue($edit['hidden']);
635 unset($edit['hidden']);
636 $this->drupalPostForm(NULL, $edit, t('Submit'));
637 $returned_values['hijacked'] = Json::decode($this->getSession()->getPage()->getContent());
639 // Ensure that the returned values match the form's default values in both
641 foreach ($returned_values as $values) {
642 $this->assertFormValuesDefault($values, $form);
647 * Assert that the values submitted to a form matches the default values of the elements.
649 public function assertFormValuesDefault($values, $form) {
650 foreach (Element::children($form) as $key) {
651 if (isset($form[$key]['#default_value'])) {
652 if (isset($form[$key]['#expected_value'])) {
653 $expected_value = $form[$key]['#expected_value'];
656 $expected_value = $form[$key]['#default_value'];
659 if ($key == 'checkboxes_multiple') {
660 // Checkboxes values are not filtered out.
661 $values[$key] = array_filter($values[$key]);
663 $this->assertIdentical($expected_value, $values[$key], format_string('Default value for %type: expected %expected, returned %returned.', ['%type' => $key, '%expected' => var_export($expected_value, TRUE), '%returned' => var_export($values[$key], TRUE)]));
667 $this->assertFormValuesDefault($values, $form[$key]);
672 * Verify markup for disabled form elements.
674 * @see _form_test_disabled_elements()
676 public function testDisabledMarkup() {
677 $this->drupalGet('form-test/disabled-elements');
678 $form = \Drupal::formBuilder()->getForm('\Drupal\form_test\Form\FormTestDisabledElementsForm');
680 'textarea' => 'textarea',
681 'select' => 'select',
682 'weight' => 'select',
683 'datetime' => 'datetime',
686 foreach ($form as $name => $item) {
687 // Skip special #types.
688 if (!isset($item['#type']) || in_array($item['#type'], ['hidden', 'text_format'])) {
691 // Setup XPath and CSS class depending on #type.
692 if (in_array($item['#type'], ['button', 'submit'])) {
693 $path = "//!type[contains(@class, :div-class) and @value=:value]";
694 $class = 'is-disabled';
696 elseif (in_array($item['#type'], ['image_button'])) {
697 $path = "//!type[contains(@class, :div-class) and @value=:value]";
698 $class = 'is-disabled';
701 // starts-with() required for checkboxes.
702 $path = "//div[contains(@class, :div-class)]/descendant::!type[starts-with(@name, :name)]";
703 $class = 'form-disabled';
705 // Replace DOM element name in $path according to #type.
707 if (isset($type_map[$item['#type']])) {
708 $type = $type_map[$item['#type']];
710 if (isset($item['#value']) && is_object($item['#value'])) {
711 $item['#value'] = (string) $item['#value'];
713 $path = strtr($path, ['!type' => $type]);
714 // Verify that the element exists.
715 $element = $this->xpath($path, [
716 ':name' => Html::escape($name),
717 ':div-class' => $class,
718 ':value' => isset($item['#value']) ? $item['#value'] : '',
720 $this->assertTrue(isset($element[0]), format_string('Disabled form element class found for #type %type.', ['%type' => $item['#type']]));
723 // Verify special element #type text-format.
724 $element = $this->xpath('//div[contains(@class, :div-class)]/descendant::textarea[@name=:name]', [
725 ':name' => 'text_format[value]',
726 ':div-class' => 'form-disabled',
728 $this->assertTrue(isset($element[0]), format_string('Disabled form element class found for #type %type.', ['%type' => 'text_format[value]']));
729 $element = $this->xpath('//div[contains(@class, :div-class)]/descendant::select[@name=:name]', [
730 ':name' => 'text_format[format]',
731 ':div-class' => 'form-disabled',
733 $this->assertTrue(isset($element[0]), format_string('Disabled form element class found for #type %type.', ['%type' => 'text_format[format]']));
737 * Test Form API protections against input forgery.
739 * @see \Drupal\form_test\Form\FormTestInputForgeryForm
741 public function testInputForgery() {
742 $this->drupalGet('form-test/input-forgery');
743 // The value for checkboxes[two] was changed using post render to simulate
745 // @see \Drupal\form_test\Form\FormTestInputForgeryForm::postRender
746 $this->drupalPostForm(NULL, ['checkboxes[one]' => TRUE, 'checkboxes[two]' => TRUE], t('Submit'));
747 $this->assertText('An illegal choice has been detected.', 'Input forgery was detected.');
751 * Tests required attribute.
753 public function testRequiredAttribute() {
754 $this->drupalGet('form-test/required-attribute');
755 $expected = 'required';
756 // Test to make sure the elements have the proper required attribute.
757 foreach (['textfield', 'password'] as $type) {
758 $element = $this->xpath('//input[@id=:id and @required=:expected]', [
759 ':id' => 'edit-' . $type,
760 ':expected' => $expected,
762 $this->assertTrue(!empty($element), format_string('The @type has the proper required attribute.', ['@type' => $type]));
765 // Test to make sure textarea has the proper required attribute.
766 $element = $this->xpath('//textarea[@id=:id and @required=:expected]', [
767 ':id' => 'edit-textarea',
768 ':expected' => $expected,
770 $this->assertTrue(!empty($element), 'The textarea has the proper required attribute.');