3 namespace Drupal\system\Tests\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\simpletest\WebTestBase;
13 use Drupal\user\RoleInterface;
14 use Drupal\filter\Entity\FilterFormat;
17 * Tests various form element validation mechanisms.
21 class FormTest extends WebTestBase {
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[0], $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.
244 'textfield' => $this->randomString(),
245 'checkboxes[bar]' => TRUE,
248 'form_token' => 'invalid token',
250 $this->drupalPostForm(Url::fromRoute('form_test.validate_required'), $edit, 'Submit');
251 $this->assertFieldByXpath('//div[contains(@class, "error")]', NULL, 'Error message is displayed with invalid token even when required fields are filled.');
252 $this->assertText('The form has become outdated. Copy any unsaved work in the form below');
253 // Verify that input elements retained the posted values.
254 $this->assertFieldByName('textfield', $edit['textfield']);
255 $this->assertNoFieldChecked('edit-checkboxes-foo');
256 $this->assertFieldChecked('edit-checkboxes-bar');
257 $this->assertOptionSelected('edit-select', 'bar');
258 $this->assertFieldChecked('edit-radios-foo');
260 // Check another form that has a textarea input.
262 'textfield' => $this->randomString(),
263 'textarea' => $this->randomString() . "\n",
264 'form_token' => 'invalid token',
266 $this->drupalPostForm(Url::fromRoute('form_test.required'), $edit, 'Submit');
267 $this->assertFieldByXpath('//div[contains(@class, "error")]', NULL, 'Error message is displayed with invalid token even when required fields are filled.');
268 $this->assertText('The form has become outdated. Copy any unsaved work in the form below');
269 $this->assertFieldByName('textfield', $edit['textfield']);
270 $this->assertFieldByName('textarea', $edit['textarea']);
272 // Check another form that has a number input.
274 'integer_step' => mt_rand(1, 100),
275 'form_token' => 'invalid token',
277 $this->drupalPostForm(Url::fromRoute('form_test.number'), $edit, 'Submit');
278 $this->assertFieldByXpath('//div[contains(@class, "error")]', NULL, 'Error message is displayed with invalid token even when required fields are filled.');
279 $this->assertText('The form has become outdated. Copy any unsaved work in the form below');
280 $this->assertFieldByName('integer_step', $edit['integer_step']);
282 // Check a form with a Url field
284 'url' => $this->randomString(),
285 'form_token' => 'invalid token',
287 $this->drupalPostForm(Url::fromRoute('form_test.url'), $edit, 'Submit');
288 $this->assertFieldByXpath('//div[contains(@class, "error")]', NULL, 'Error message is displayed with invalid token even when required fields are filled.');
289 $this->assertText('The form has become outdated. Copy any unsaved work in the form below');
290 $this->assertFieldByName('url', $edit['url']);
294 * CSRF tokens for GET forms should not be added by default.
296 public function testGetFormsCsrfToken() {
297 // We need to be logged in to have CSRF tokens.
298 $account = $this->createUser();
299 $this->drupalLogin($account);
301 $this->drupalGet(Url::fromRoute('form_test.get_form'));
302 $this->assertNoRaw('form_token');
306 * Tests validation for required textfield element without title.
308 * Submits a test form containing a textfield form element without title.
309 * The form is submitted twice, first without value for the required field
310 * and then with value. Each submission is checked for relevant error
313 * @see \Drupal\form_test\Form\FormTestValidateRequiredNoTitleForm
315 public function testRequiredTextfieldNoTitle() {
316 // Attempt to submit the form with no required field set.
318 $this->drupalPostForm('form-test/validate-required-no-title', $edit, 'Submit');
319 $this->assertNoRaw("The form_test_validate_required_form_no_title form was submitted successfully.", 'Validation form submitted successfully.');
321 // Check the page for the error class on the textfield.
322 $this->assertFieldByXPath('//input[contains(@class, "error")]', FALSE, 'Error input form element class found.');
324 // Check the page for the aria-invalid attribute on the textfield.
325 $this->assertFieldByXPath('//input[contains(@aria-invalid, "true")]', FALSE, 'Aria invalid attribute found.');
327 // Submit again with required fields set and verify that there are no
330 'textfield' => $this->randomString(),
332 $this->drupalPostForm(NULL, $edit, 'Submit');
333 $this->assertNoFieldByXpath('//input[contains(@class, "error")]', FALSE, 'No error input form element class found.');
334 $this->assertRaw("The form_test_validate_required_form_no_title form was submitted successfully.", 'Validation form submitted successfully.');
338 * Test default value handling for checkboxes.
340 * @see _form_test_checkbox()
342 public function testCheckboxProcessing() {
343 // First, try to submit without the required checkbox.
345 $this->drupalPostForm('form-test/checkbox', $edit, t('Submit'));
346 $this->assertRaw(t('@name field is required.', ['@name' => 'required_checkbox']), 'A required checkbox is actually mandatory');
348 // Now try to submit the form correctly.
349 $values = Json::decode($this->drupalPostForm(NULL, ['required_checkbox' => 1], t('Submit')));
351 'disabled_checkbox_on' => 'disabled_checkbox_on',
352 'disabled_checkbox_off' => '',
353 'checkbox_on' => 'checkbox_on',
354 'checkbox_off' => '',
355 'zero_checkbox_on' => '0',
356 'zero_checkbox_off' => '',
358 foreach ($expected_values as $widget => $expected_value) {
359 $this->assertEqual($values[$widget], $expected_value, format_string('Checkbox %widget returns expected value (expected: %expected, got: %value)', [
360 '%widget' => var_export($widget, TRUE),
361 '%expected' => var_export($expected_value, TRUE),
362 '%value' => var_export($values[$widget], TRUE),
368 * Tests validation of #type 'select' elements.
370 public function testSelect() {
371 $form = \Drupal::formBuilder()->getForm('Drupal\form_test\Form\FormTestSelectForm');
372 $this->drupalGet('form-test/select');
374 // Verify that the options are escaped as expected.
375 $this->assertEscaped('<strong>four</strong>');
376 $this->assertNoRaw('<strong>four</strong>');
378 // Posting without any values should throw validation errors.
379 $this->drupalPostForm(NULL, [], 'Submit');
386 'no_default_optional',
387 'no_default_empty_option_optional',
388 'no_default_empty_value_optional',
390 'multiple_no_default',
392 foreach ($no_errors as $key) {
393 $this->assertNoText(t('@name field is required.', ['@name' => $form[$key]['#title']]));
398 'no_default_empty_option',
399 'no_default_empty_value',
400 'no_default_empty_value_one',
401 'multiple_no_default_required',
403 foreach ($expected_errors as $key) {
404 $this->assertText(t('@name field is required.', ['@name' => $form[$key]['#title']]));
407 // Post values for required fields.
409 'no_default' => 'three',
410 'no_default_empty_option' => 'three',
411 'no_default_empty_value' => 'three',
412 'no_default_empty_value_one' => 'three',
413 'multiple_no_default_required[]' => 'three',
415 $this->drupalPostForm(NULL, $edit, 'Submit');
416 $values = Json::decode($this->getRawContent());
418 // Verify expected values.
421 'empty_value' => 'one',
422 'empty_value_one' => 'one',
423 'no_default' => 'three',
424 'no_default_optional' => 'one',
425 'no_default_optional_empty_value' => '',
426 'no_default_empty_option' => 'three',
427 'no_default_empty_option_optional' => '',
428 'no_default_empty_value' => 'three',
429 'no_default_empty_value_one' => 'three',
430 'no_default_empty_value_optional' => 0,
431 'multiple' => ['two' => 'two'],
432 'multiple_no_default' => [],
433 'multiple_no_default_required' => ['three' => 'three'],
435 foreach ($expected as $key => $value) {
436 $this->assertIdentical($values[$key], $value, format_string('@name: @actual is equal to @expected.', [
438 '@actual' => var_export($values[$key], TRUE),
439 '@expected' => var_export($value, TRUE),
445 * Tests a select element when #options is not set.
447 public function testEmptySelect() {
448 $this->drupalGet('form-test/empty-select');
449 $this->assertFieldByXPath("//select[1]", NULL, 'Select element found.');
450 $this->assertNoFieldByXPath("//select[1]/option", NULL, 'No option element found.');
454 * Tests validation of #type 'number' and 'range' elements.
456 public function testNumber() {
457 $form = \Drupal::formBuilder()->getForm('\Drupal\form_test\Form\FormTestNumberForm');
459 // Array with all the error messages to be checked.
461 'no_number' => '%name must be a number.',
462 'too_low' => '%name must be higher than or equal to %min.',
463 'too_high' => '%name must be lower than or equal to %max.',
464 'step_mismatch' => '%name is not a valid number.',
467 // The expected errors.
469 'integer_no_number' => 'no_number',
470 'integer_no_step' => 0,
471 'integer_no_step_step_error' => 'step_mismatch',
473 'integer_step_error' => 'step_mismatch',
474 'integer_step_min' => 0,
475 'integer_step_min_error' => 'too_low',
476 'integer_step_max' => 0,
477 'integer_step_max_error' => 'too_high',
478 'integer_step_min_border' => 0,
479 'integer_step_max_border' => 0,
480 'integer_step_based_on_min' => 0,
481 'integer_step_based_on_min_error' => 'step_mismatch',
482 'float_small_step' => 0,
483 'float_step_no_error' => 0,
484 'float_step_error' => 'step_mismatch',
485 'float_step_hard_no_error' => 0,
486 'float_step_hard_error' => 'step_mismatch',
487 'float_step_any_no_error' => 0,
490 // First test the number element type, then range.
491 foreach (['form-test/number', 'form-test/number/range'] as $path) {
492 // Post form and show errors.
493 $this->drupalPostForm($path, [], 'Submit');
495 foreach ($expected as $element => $error) {
496 // Create placeholder array.
498 '%name' => $form[$element]['#title'],
499 '%min' => isset($form[$element]['#min']) ? $form[$element]['#min'] : '0',
500 '%max' => isset($form[$element]['#max']) ? $form[$element]['#max'] : '0',
503 foreach ($error_messages as $id => $message) {
504 // Check if the error exists on the page, if the current message ID is
505 // expected. Otherwise ensure that the error message is not present.
506 if ($id === $error) {
507 $this->assertRaw(format_string($message, $placeholders));
510 $this->assertNoRaw(format_string($message, $placeholders));
518 * Tests default value handling of #type 'range' elements.
520 public function testRange() {
521 $values = json_decode($this->drupalPostForm('form-test/range', [], 'Submit'));
522 $this->assertEqual($values->with_default_value, 18);
523 $this->assertEqual($values->float, 10.5);
524 $this->assertEqual($values->integer, 6);
525 $this->assertEqual($values->offset, 6.9);
527 $this->drupalPostForm('form-test/range/invalid', [], 'Submit');
528 $this->assertFieldByXPath('//input[@type="range" and contains(@class, "error")]', NULL, 'Range element has the error class.');
532 * Tests validation of #type 'color' elements.
534 public function testColorValidation() {
535 // Keys are inputs, values are expected results.
540 '#af0DEE' => '#af0dee',
541 '#99ccBc' => '#99ccbc',
542 '#aabbcc' => '#aabbcc',
543 '123456' => '#123456',
546 // Tests that valid values are properly normalized.
547 foreach ($values as $input => $expected) {
551 $result = json_decode($this->drupalPostForm('form-test/color', $edit, 'Submit'));
552 $this->assertEqual($result->color, $expected);
555 // Tests invalid values are rejected.
556 $values = ['#0008', '#1234', '#fffffg', '#abcdef22', '17', '#uaa'];
557 foreach ($values as $input) {
561 $this->drupalPostForm('form-test/color', $edit, 'Submit');
562 $this->assertRaw(t('%name must be a valid color.', ['%name' => 'Color']));
567 * Test handling of disabled elements.
569 * @see _form_test_disabled_elements()
571 public function testDisabledElements() {
572 // Get the raw form in its original state.
573 $form_state = new FormState();
574 $form = (new FormTestDisabledElementsForm())->buildForm([], $form_state);
576 // Build a submission that tries to hijack the form by submitting input for
577 // elements that are disabled.
579 foreach (Element::children($form) as $key) {
580 if (isset($form[$key]['#test_hijack_value'])) {
581 if (is_array($form[$key]['#test_hijack_value'])) {
582 foreach ($form[$key]['#test_hijack_value'] as $subkey => $value) {
583 $edit[$key . '[' . $subkey . ']'] = $value;
587 $edit[$key] = $form[$key]['#test_hijack_value'];
592 // Submit the form with no input, as the browser does for disabled elements,
593 // and fetch the $form_state->getValues() that is passed to the submit handler.
594 $this->drupalPostForm('form-test/disabled-elements', [], t('Submit'));
595 $returned_values['normal'] = Json::decode($this->content);
597 // Do the same with input, as could happen if JavaScript un-disables an
598 // element. drupalPostForm() emulates a browser by not submitting input for
599 // disabled elements, so we need to un-disable those elements first.
600 $this->drupalGet('form-test/disabled-elements');
601 $disabled_elements = [];
602 foreach ($this->xpath('//*[@disabled]') as $element) {
603 $disabled_elements[] = (string) $element['name'];
604 unset($element['disabled']);
607 // All the elements should be marked as disabled, including the ones below
608 // the disabled container.
609 $actual_count = count($disabled_elements);
610 $expected_count = 42;
611 $this->assertEqual($actual_count, $expected_count, SafeMarkup::format('Found @actual elements with disabled property (expected @expected).', [
612 '@actual' => count($disabled_elements),
613 '@expected' => $expected_count,
616 $this->drupalPostForm(NULL, $edit, t('Submit'));
617 $returned_values['hijacked'] = Json::decode($this->content);
619 // Ensure that the returned values match the form's default values in both
621 foreach ($returned_values as $values) {
622 $this->assertFormValuesDefault($values, $form);
627 * Assert that the values submitted to a form matches the default values of the elements.
629 public function assertFormValuesDefault($values, $form) {
630 foreach (Element::children($form) as $key) {
631 if (isset($form[$key]['#default_value'])) {
632 if (isset($form[$key]['#expected_value'])) {
633 $expected_value = $form[$key]['#expected_value'];
636 $expected_value = $form[$key]['#default_value'];
639 if ($key == 'checkboxes_multiple') {
640 // Checkboxes values are not filtered out.
641 $values[$key] = array_filter($values[$key]);
643 $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)]));
647 $this->assertFormValuesDefault($values, $form[$key]);
652 * Verify markup for disabled form elements.
654 * @see _form_test_disabled_elements()
656 public function testDisabledMarkup() {
657 $this->drupalGet('form-test/disabled-elements');
658 $form = \Drupal::formBuilder()->getForm('\Drupal\form_test\Form\FormTestDisabledElementsForm');
660 'textarea' => 'textarea',
661 'select' => 'select',
662 'weight' => 'select',
663 'datetime' => 'datetime',
666 foreach ($form as $name => $item) {
667 // Skip special #types.
668 if (!isset($item['#type']) || in_array($item['#type'], ['hidden', 'text_format'])) {
671 // Setup XPath and CSS class depending on #type.
672 if (in_array($item['#type'], ['button', 'submit'])) {
673 $path = "//!type[contains(@class, :div-class) and @value=:value]";
674 $class = 'is-disabled';
676 elseif (in_array($item['#type'], ['image_button'])) {
677 $path = "//!type[contains(@class, :div-class) and @value=:value]";
678 $class = 'is-disabled';
681 // starts-with() required for checkboxes.
682 $path = "//div[contains(@class, :div-class)]/descendant::!type[starts-with(@name, :name)]";
683 $class = 'form-disabled';
685 // Replace DOM element name in $path according to #type.
687 if (isset($type_map[$item['#type']])) {
688 $type = $type_map[$item['#type']];
690 $path = strtr($path, ['!type' => $type]);
691 // Verify that the element exists.
692 $element = $this->xpath($path, [
693 ':name' => Html::escape($name),
694 ':div-class' => $class,
695 ':value' => isset($item['#value']) ? $item['#value'] : '',
697 $this->assertTrue(isset($element[0]), format_string('Disabled form element class found for #type %type.', ['%type' => $item['#type']]));
700 // Verify special element #type text-format.
701 $element = $this->xpath('//div[contains(@class, :div-class)]/descendant::textarea[@name=:name]', [
702 ':name' => 'text_format[value]',
703 ':div-class' => 'form-disabled',
705 $this->assertTrue(isset($element[0]), format_string('Disabled form element class found for #type %type.', ['%type' => 'text_format[value]']));
706 $element = $this->xpath('//div[contains(@class, :div-class)]/descendant::select[@name=:name]', [
707 ':name' => 'text_format[format]',
708 ':div-class' => 'form-disabled',
710 $this->assertTrue(isset($element[0]), format_string('Disabled form element class found for #type %type.', ['%type' => 'text_format[format]']));
714 * Test Form API protections against input forgery.
716 * @see _form_test_input_forgery()
718 public function testInputForgery() {
719 $this->drupalGet('form-test/input-forgery');
720 $checkbox = $this->xpath('//input[@name="checkboxes[two]"]');
721 $checkbox[0]['value'] = 'FORGERY';
722 $this->drupalPostForm(NULL, ['checkboxes[one]' => TRUE, 'checkboxes[two]' => TRUE], t('Submit'));
723 $this->assertText('An illegal choice has been detected.', 'Input forgery was detected.');
727 * Tests required attribute.
729 public function testRequiredAttribute() {
730 $this->drupalGet('form-test/required-attribute');
731 $expected = 'required';
732 // Test to make sure the elements have the proper required attribute.
733 foreach (['textfield', 'password'] as $type) {
734 $element = $this->xpath('//input[@id=:id and @required=:expected]', [
735 ':id' => 'edit-' . $type,
736 ':expected' => $expected,
738 $this->assertTrue(!empty($element), format_string('The @type has the proper required attribute.', ['@type' => $type]));
741 // Test to make sure textarea has the proper required attribute.
742 $element = $this->xpath('//textarea[@id=:id and @required=:expected]', [
743 ':id' => 'edit-textarea',
744 ':expected' => $expected,
746 $this->assertTrue(!empty($element), 'The textarea has the proper required attribute.');