Version 1
[yaffs-website] / web / core / modules / system / tests / modules / form_test / src / Form / FormTestCheckboxForm.php
1 <?php
2
3 namespace Drupal\form_test\Form;
4
5 use Drupal\Core\Form\FormBase;
6 use Drupal\Core\Form\FormStateInterface;
7 use Symfony\Component\HttpFoundation\JsonResponse;
8
9 class FormTestCheckboxForm extends FormBase {
10
11   /**
12    * {@inheritdoc}
13    */
14   public function getFormId() {
15     return '_test_checkbox_form';
16   }
17
18   /**
19    * {@inheritdoc}
20    */
21   public function buildForm(array $form, FormStateInterface $form_state) {
22     // A required checkbox.
23     $form['required_checkbox'] = [
24       '#type' => 'checkbox',
25       '#required' => TRUE,
26       '#title' => 'required_checkbox',
27     ];
28
29     // A disabled checkbox should get its default value back.
30     $form['disabled_checkbox_on'] = [
31       '#type' => 'checkbox',
32       '#disabled' => TRUE,
33       '#return_value' => 'disabled_checkbox_on',
34       '#default_value' => 'disabled_checkbox_on',
35       '#title' => 'disabled_checkbox_on',
36     ];
37     $form['disabled_checkbox_off'] = [
38       '#type' => 'checkbox',
39       '#disabled' => TRUE,
40       '#return_value' => 'disabled_checkbox_off',
41       '#default_value' => NULL,
42       '#title' => 'disabled_checkbox_off',
43     ];
44
45     // A checkbox is active when #default_value == #return_value.
46     $form['checkbox_on'] = [
47       '#type' => 'checkbox',
48       '#return_value' => 'checkbox_on',
49       '#default_value' => 'checkbox_on',
50       '#title' => 'checkbox_on',
51     ];
52
53     // But inactive in any other case.
54     $form['checkbox_off'] = [
55       '#type' => 'checkbox',
56       '#return_value' => 'checkbox_off',
57       '#default_value' => 'checkbox_on',
58       '#title' => 'checkbox_off',
59     ];
60
61     // Checkboxes with a #return_value of '0' are supported.
62     $form['zero_checkbox_on'] = [
63       '#type' => 'checkbox',
64       '#return_value' => '0',
65       '#default_value' => '0',
66       '#title' => 'zero_checkbox_on',
67     ];
68
69     // In that case, passing a #default_value != '0'
70     // means that the checkbox is off.
71     $form['zero_checkbox_off'] = [
72       '#type' => 'checkbox',
73       '#return_value' => '0',
74       '#default_value' => '1',
75       '#title' => 'zero_checkbox_off',
76     ];
77
78     $form['submit'] = [
79       '#type' => 'submit',
80       '#value' => t('Submit'),
81     ];
82
83     return $form;
84   }
85
86   /**
87    * {@inheritdoc}
88    */
89   public function submitForm(array &$form, FormStateInterface $form_state) {
90     $form_state->setResponse(new JsonResponse($form_state->getValues()));
91   }
92
93 }