3 namespace Drupal\form_test\Form;
5 use Drupal\Core\Form\FormBase;
6 use Drupal\Core\Form\FormStateInterface;
7 use Symfony\Component\HttpFoundation\JsonResponse;
9 class FormTestCheckboxForm extends FormBase {
14 public function getFormId() {
15 return '_test_checkbox_form';
21 public function buildForm(array $form, FormStateInterface $form_state) {
22 // A required checkbox.
23 $form['required_checkbox'] = [
24 '#type' => 'checkbox',
26 '#title' => 'required_checkbox',
29 // A disabled checkbox should get its default value back.
30 $form['disabled_checkbox_on'] = [
31 '#type' => 'checkbox',
33 '#return_value' => 'disabled_checkbox_on',
34 '#default_value' => 'disabled_checkbox_on',
35 '#title' => 'disabled_checkbox_on',
37 $form['disabled_checkbox_off'] = [
38 '#type' => 'checkbox',
40 '#return_value' => 'disabled_checkbox_off',
41 '#default_value' => NULL,
42 '#title' => 'disabled_checkbox_off',
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',
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',
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',
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',
80 '#value' => t('Submit'),
89 public function submitForm(array &$form, FormStateInterface $form_state) {
90 $form_state->setResponse(new JsonResponse($form_state->getValues()));