Version 1
[yaffs-website] / web / core / modules / system / src / Tests / Ajax / FormValuesTest.php
1 <?php
2
3 namespace Drupal\system\Tests\Ajax;
4
5 use Drupal\Core\Ajax\DataCommand;
6
7 /**
8  * Tests that form values are properly delivered to AJAX callbacks.
9  *
10  * @group Ajax
11  */
12 class FormValuesTest extends AjaxTestBase {
13   protected function setUp() {
14     parent::setUp();
15
16     $this->drupalLogin($this->drupalCreateUser(['access content']));
17   }
18
19   /**
20    * Submits forms with select and checkbox elements via Ajax.
21    */
22   public function testSimpleAjaxFormValue() {
23     // Verify form values of a select element.
24     foreach (['red', 'green', 'blue'] as $item) {
25       $edit = [
26         'select' => $item,
27       ];
28       $commands = $this->drupalPostAjaxForm('ajax_forms_test_get_form', $edit, 'select');
29       $expected = new DataCommand('#ajax_selected_color', 'form_state_value_select', $item);
30       $this->assertCommand($commands, $expected->render(), 'Verification of AJAX form values from a selectbox issued with a correct value.');
31     }
32
33     // Verify form values of a checkbox element.
34     foreach ([FALSE, TRUE] as $item) {
35       $edit = [
36         'checkbox' => $item,
37       ];
38       $commands = $this->drupalPostAjaxForm('ajax_forms_test_get_form', $edit, 'checkbox');
39       $expected = new DataCommand('#ajax_checkbox_value', 'form_state_value_select', (int) $item);
40       $this->assertCommand($commands, $expected->render(), 'Verification of AJAX form values from a checkbox issued with a correct value.');
41     }
42
43     // Verify that AJAX elements with invalid callbacks return error code 500.
44     // Ensure the test error log is empty before these tests.
45     $this->assertNoErrorsLogged();
46     // We don't need to check for the X-Drupal-Ajax-Token header with these
47     // invalid requests.
48     $this->assertAjaxHeader = FALSE;
49     foreach (['null', 'empty', 'nonexistent'] as $key) {
50       $element_name = 'select_' . $key . '_callback';
51       $edit = [
52         $element_name => 'red',
53       ];
54       $commands = $this->drupalPostAjaxForm('ajax_forms_test_get_form', $edit, $element_name);
55       $this->assertResponse(500);
56     }
57     // Switch this back to the default.
58     $this->assertAjaxHeader = TRUE;
59     // The exceptions are expected. Do not interpret them as a test failure.
60     // Not using File API; a potential error must trigger a PHP warning.
61     unlink(\Drupal::root() . '/' . $this->siteDirectory . '/error.log');
62   }
63
64 }