4b8d042faa28676846e0e2843c568ff2969f90b0
[yaffs-website] / web / core / modules / system / src / Tests / Form / FormTest.php
1 <?php
2
3 namespace Drupal\system\Tests\Form;
4
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;
10 use Drupal\Core\Url;
11 use Drupal\form_test\Form\FormTestDisabledElementsForm;
12 use Drupal\simpletest\WebTestBase;
13 use Drupal\user\RoleInterface;
14 use Drupal\filter\Entity\FilterFormat;
15
16 /**
17  * Tests various form element validation mechanisms.
18  *
19  * @group Form
20  */
21 class FormTest extends WebTestBase {
22
23   /**
24    * Modules to enable.
25    *
26    * @var array
27    */
28   public static $modules = ['filter', 'form_test', 'file', 'datetime'];
29
30   protected function setUp() {
31     parent::setUp();
32
33     $filtered_html_format = FilterFormat::create([
34       'format' => 'filtered_html',
35       'name' => 'Filtered HTML',
36     ]);
37     $filtered_html_format->save();
38
39     $filtered_html_permission = $filtered_html_format->getPermissionName();
40     user_role_grant_permissions(RoleInterface::ANONYMOUS_ID, [$filtered_html_permission]);
41   }
42
43   /**
44    * Check several empty values for required forms elements.
45    *
46    * Carriage returns, tabs, spaces, and unchecked checkbox elements are not
47    * valid content for a required field.
48    *
49    * If the form field is found in $form_state->getErrors() then the test pass.
50    */
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];
57
58     $elements['textfield']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'textfield'];
59     $elements['textfield']['empty_values'] = $empty_strings;
60
61     $elements['telephone']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'tel'];
62     $elements['telephone']['empty_values'] = $empty_strings;
63
64     $elements['url']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'url'];
65     $elements['url']['empty_values'] = $empty_strings;
66
67     $elements['search']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'search'];
68     $elements['search']['empty_values'] = $empty_strings;
69
70     $elements['password']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'password'];
71     $elements['password']['empty_values'] = $empty_strings;
72
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];
77     }
78
79     $elements['textarea']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'textarea'];
80     $elements['textarea']['empty_values'] = $empty_strings;
81
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;
84
85     $elements['checkbox']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'checkbox', '#required' => TRUE];
86     $elements['checkbox']['empty_values'] = $empty_checkbox;
87
88     $elements['checkboxes']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'checkboxes', '#options' => [$this->randomMachineName(), $this->randomMachineName(), $this->randomMachineName()]];
89     $elements['checkboxes']['empty_values'] = $empty_arrays;
90
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;
93
94     $elements['file']['element'] = ['#title' => $this->randomMachineName(), '#type' => 'file'];
95     $elements['file']['empty_values'] = $empty_strings;
96
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();
104           $form = [];
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);
126           if ($required) {
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");
132             }
133           }
134           else {
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");
138             }
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");
144             }
145             else {
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");
148             }
149           }
150         }
151       }
152     }
153     // Clear the expected form error messages so they don't appear as exceptions.
154     drupal_get_messages();
155   }
156
157   /**
158    * Tests validation for required checkbox, select, and radio elements.
159    *
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.
163    *
164    * @see \Drupal\form_test\Form\FormTestValidateRequiredForm
165    */
166   public function testRequiredCheckboxesRadio() {
167     $form = \Drupal::formBuilder()->getForm('\Drupal\form_test\Form\FormTestValidateRequiredForm');
168
169     // Attempt to submit the form with no required fields set.
170     $edit = [];
171     $this->drupalPostForm('form-test/validate-required', $edit, 'Submit');
172
173     // The only error messages that should appear are the relevant 'required'
174     // messages for each field.
175     $expected = [];
176     foreach (['textfield', 'checkboxes', 'select', 'radios'] as $key) {
177       if (isset($form[$key]['#required_error'])) {
178         $expected[] = $form[$key]['#required_error'];
179       }
180       elseif (isset($form[$key]['#form_test_required_error'])) {
181         $expected[] = $form[$key]['#form_test_required_error'];
182       }
183       else {
184         $expected[] = t('@name field is required.', ['@name' => $form[$key]['#title']]);
185       }
186     }
187
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]]));
195       }
196       // Remove the expected message from the list once it is found.
197       else {
198         unset($expected[$expected_key]);
199       }
200     }
201
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]));
205     }
206
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');
218
219     // Submit again with required fields set and verify that there are no
220     // error messages.
221     $edit = [
222       'textfield' => $this->randomString(),
223       'checkboxes[foo]' => TRUE,
224       'select' => 'foo',
225       'radios' => 'bar',
226     ];
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.');
230   }
231
232   /**
233    * Tests that input is retained for safe elements even with an invalid token.
234    *
235    * Submits a test form containing several types of form elements.
236    */
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     $edit = [
244       'textfield' => $this->randomString(),
245       'checkboxes[bar]' => TRUE,
246       'select' => 'bar',
247       'radios' => 'foo',
248       'form_token' => 'invalid token',
249     ];
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');
259
260     // Check another form that has a textarea input.
261     $edit = [
262       'textfield' => $this->randomString(),
263       'textarea' => $this->randomString() . "\n",
264       'form_token' => 'invalid token',
265     ];
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']);
271
272     // Check another form that has a number input.
273     $edit = [
274       'integer_step' => mt_rand(1, 100),
275       'form_token' => 'invalid token',
276     ];
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']);
281
282     // Check a form with a Url field
283     $edit = [
284       'url' => $this->randomString(),
285       'form_token' => 'invalid token',
286     ];
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']);
291   }
292
293   /**
294    * CSRF tokens for GET forms should not be added by default.
295    */
296   public function testGetFormsCsrfToken() {
297     // We need to be logged in to have CSRF tokens.
298     $account = $this->createUser();
299     $this->drupalLogin($account);
300
301     $this->drupalGet(Url::fromRoute('form_test.get_form'));
302     $this->assertNoRaw('form_token');
303   }
304
305   /**
306    * Tests validation for required textfield element without title.
307    *
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
311    * messages.
312    *
313    * @see \Drupal\form_test\Form\FormTestValidateRequiredNoTitleForm
314    */
315   public function testRequiredTextfieldNoTitle() {
316     // Attempt to submit the form with no required field set.
317     $edit = [];
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.');
320
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.');
323
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.');
326
327     // Submit again with required fields set and verify that there are no
328     // error messages.
329     $edit = [
330       'textfield' => $this->randomString(),
331     ];
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.');
335   }
336
337   /**
338    * Test default value handling for checkboxes.
339    *
340    * @see _form_test_checkbox()
341    */
342   public function testCheckboxProcessing() {
343     // First, try to submit without the required checkbox.
344     $edit = [];
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');
347
348     // Now try to submit the form correctly.
349     $values = Json::decode($this->drupalPostForm(NULL, ['required_checkbox' => 1], t('Submit')));
350     $expected_values = [
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' => '',
357     ];
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),
363       ]));
364     }
365   }
366
367   /**
368    * Tests validation of #type 'select' elements.
369    */
370   public function testSelect() {
371     $form = \Drupal::formBuilder()->getForm('Drupal\form_test\Form\FormTestSelectForm');
372     $this->drupalGet('form-test/select');
373
374     // Verify that the options are escaped as expected.
375     $this->assertEscaped('<strong>four</strong>');
376     $this->assertNoRaw('<strong>four</strong>');
377
378     // Posting without any values should throw validation errors.
379     $this->drupalPostForm(NULL, [], 'Submit');
380     $no_errors = [
381         'select',
382         'select_required',
383         'select_optional',
384         'empty_value',
385         'empty_value_one',
386         'no_default_optional',
387         'no_default_empty_option_optional',
388         'no_default_empty_value_optional',
389         'multiple',
390         'multiple_no_default',
391     ];
392     foreach ($no_errors as $key) {
393       $this->assertNoText(t('@name field is required.', ['@name' => $form[$key]['#title']]));
394     }
395
396     $expected_errors = [
397         'no_default',
398         'no_default_empty_option',
399         'no_default_empty_value',
400         'no_default_empty_value_one',
401         'multiple_no_default_required',
402     ];
403     foreach ($expected_errors as $key) {
404       $this->assertText(t('@name field is required.', ['@name' => $form[$key]['#title']]));
405     }
406
407     // Post values for required fields.
408     $edit = [
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',
414     ];
415     $this->drupalPostForm(NULL, $edit, 'Submit');
416     $values = Json::decode($this->getRawContent());
417
418     // Verify expected values.
419     $expected = [
420       'select' => 'one',
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'],
434     ];
435     foreach ($expected as $key => $value) {
436       $this->assertIdentical($values[$key], $value, format_string('@name: @actual is equal to @expected.', [
437         '@name' => $key,
438         '@actual' => var_export($values[$key], TRUE),
439         '@expected' => var_export($value, TRUE),
440       ]));
441     }
442   }
443
444   /**
445    * Tests a select element when #options is not set.
446    */
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.');
451   }
452
453   /**
454    * Tests validation of #type 'number' and 'range' elements.
455    */
456   public function testNumber() {
457     $form = \Drupal::formBuilder()->getForm('\Drupal\form_test\Form\FormTestNumberForm');
458
459     // Array with all the error messages to be checked.
460     $error_messages = [
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.',
465     ];
466
467     // The expected errors.
468     $expected = [
469       'integer_no_number' => 'no_number',
470       'integer_no_step' => 0,
471       'integer_no_step_step_error' => 'step_mismatch',
472       'integer_step' => 0,
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,
488     ];
489
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');
494
495       foreach ($expected as $element => $error) {
496         // Create placeholder array.
497         $placeholders = [
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',
501         ];
502
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));
508           }
509           else {
510             $this->assertNoRaw(format_string($message, $placeholders));
511           }
512         }
513       }
514     }
515   }
516
517   /**
518    * Tests default value handling of #type 'range' elements.
519    */
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);
526
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.');
529   }
530
531   /**
532    * Tests validation of #type 'color' elements.
533    */
534   public function testColorValidation() {
535     // Keys are inputs, values are expected results.
536     $values = [
537       '' => '#000000',
538       '#000' => '#000000',
539       'AAA' => '#aaaaaa',
540       '#af0DEE' => '#af0dee',
541       '#99ccBc' => '#99ccbc',
542       '#aabbcc' => '#aabbcc',
543       '123456' => '#123456',
544     ];
545
546     // Tests that valid values are properly normalized.
547     foreach ($values as $input => $expected) {
548       $edit = [
549         'color' => $input,
550       ];
551       $result = json_decode($this->drupalPostForm('form-test/color', $edit, 'Submit'));
552       $this->assertEqual($result->color, $expected);
553     }
554
555     // Tests invalid values are rejected.
556     $values = ['#0008', '#1234', '#fffffg', '#abcdef22', '17', '#uaa'];
557     foreach ($values as $input) {
558       $edit = [
559         'color' => $input,
560       ];
561       $this->drupalPostForm('form-test/color', $edit, 'Submit');
562       $this->assertRaw(t('%name must be a valid color.', ['%name' => 'Color']));
563     }
564   }
565
566   /**
567    * Test handling of disabled elements.
568    *
569    * @see _form_test_disabled_elements()
570    */
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);
575
576     // Build a submission that tries to hijack the form by submitting input for
577     // elements that are disabled.
578     $edit = [];
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;
584           }
585         }
586         else {
587           $edit[$key] = $form[$key]['#test_hijack_value'];
588         }
589       }
590     }
591
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);
596
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']);
605     }
606
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,
614     ]));
615
616     $this->drupalPostForm(NULL, $edit, t('Submit'));
617     $returned_values['hijacked'] = Json::decode($this->content);
618
619     // Ensure that the returned values match the form's default values in both
620     // cases.
621     foreach ($returned_values as $values) {
622       $this->assertFormValuesDefault($values, $form);
623     }
624   }
625
626   /**
627    * Assert that the values submitted to a form matches the default values of the elements.
628    */
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'];
634         }
635         else {
636           $expected_value = $form[$key]['#default_value'];
637         }
638
639         if ($key == 'checkboxes_multiple') {
640           // Checkboxes values are not filtered out.
641           $values[$key] = array_filter($values[$key]);
642         }
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)]));
644       }
645
646       // Recurse children.
647       $this->assertFormValuesDefault($values, $form[$key]);
648     }
649   }
650
651   /**
652    * Verify markup for disabled form elements.
653    *
654    * @see _form_test_disabled_elements()
655    */
656   public function testDisabledMarkup() {
657     $this->drupalGet('form-test/disabled-elements');
658     $form = \Drupal::formBuilder()->getForm('\Drupal\form_test\Form\FormTestDisabledElementsForm');
659     $type_map = [
660       'textarea' => 'textarea',
661       'select' => 'select',
662       'weight' => 'select',
663       'datetime' => 'datetime',
664     ];
665
666     foreach ($form as $name => $item) {
667       // Skip special #types.
668       if (!isset($item['#type']) || in_array($item['#type'], ['hidden', 'text_format'])) {
669         continue;
670       }
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';
675       }
676       elseif (in_array($item['#type'], ['image_button'])) {
677         $path = "//!type[contains(@class, :div-class) and @value=:value]";
678         $class = 'is-disabled';
679       }
680       else {
681         // starts-with() required for checkboxes.
682         $path = "//div[contains(@class, :div-class)]/descendant::!type[starts-with(@name, :name)]";
683         $class = 'form-disabled';
684       }
685       // Replace DOM element name in $path according to #type.
686       $type = 'input';
687       if (isset($type_map[$item['#type']])) {
688         $type = $type_map[$item['#type']];
689       }
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'] : '',
696       ]);
697       $this->assertTrue(isset($element[0]), format_string('Disabled form element class found for #type %type.', ['%type' => $item['#type']]));
698     }
699
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',
704     ]);
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',
709     ]);
710     $this->assertTrue(isset($element[0]), format_string('Disabled form element class found for #type %type.', ['%type' => 'text_format[format]']));
711   }
712
713   /**
714    * Test Form API protections against input forgery.
715    *
716    * @see _form_test_input_forgery()
717    */
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.');
724   }
725
726   /**
727    * Tests required attribute.
728    */
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,
737       ]);
738       $this->assertTrue(!empty($element), format_string('The @type has the proper required attribute.', ['@type' => $type]));
739     }
740
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,
745     ]);
746     $this->assertTrue(!empty($element), 'The textarea has the proper required attribute.');
747   }
748
749 }