Updated Drupal to 8.6. This goes with the following updates because it's possible...
[yaffs-website] / web / core / modules / system / tests / modules / form_test / src / Form / FormTestValidateRequiredForm.php
1 <?php
2
3 namespace Drupal\form_test\Form;
4
5 use Drupal\Core\Form\FormBase;
6 use Drupal\Core\Form\FormStateInterface;
7
8 /**
9  * Form constructor to test the #required property.
10  *
11  * @internal
12  */
13 class FormTestValidateRequiredForm extends FormBase {
14
15   /**
16    * {@inheritdoc}
17    */
18   public function getFormId() {
19     return 'form_test_validate_required_form';
20   }
21
22   /**
23    * {@inheritdoc}
24    */
25   public function buildForm(array $form, FormStateInterface $form_state) {
26     $options = ['foo' => 'foo', 'bar' => 'bar'];
27     $validate = ['::elementValidateRequired'];
28
29     $form['textfield'] = [
30       '#type' => 'textfield',
31       '#title' => 'Name',
32       '#required' => TRUE,
33       '#required_error' => t('Please enter a name.'),
34     ];
35     $form['checkboxes'] = [
36       '#type' => 'checkboxes',
37       '#title' => 'Checkboxes',
38       '#options' => $options,
39       '#required' => TRUE,
40       '#form_test_required_error' => t('Please choose at least one option.'),
41       '#element_validate' => $validate,
42     ];
43     $form['select'] = [
44       '#type' => 'select',
45       '#title' => 'Select',
46       '#options' => $options,
47       '#required' => TRUE,
48       '#form_test_required_error' => t('Please select something.'),
49       '#element_validate' => $validate,
50     ];
51     $form['radios'] = [
52       '#type' => 'radios',
53       '#title' => 'Radios',
54       '#options' => $options,
55       '#required' => TRUE,
56     ];
57     $form['radios_optional'] = [
58       '#type' => 'radios',
59       '#title' => 'Radios (optional)',
60       '#options' => $options,
61     ];
62     $form['radios_optional_default_value_false'] = [
63       '#type' => 'radios',
64       '#title' => 'Radios (optional, with a default value of FALSE)',
65       '#options' => $options,
66       '#default_value' => FALSE,
67     ];
68     $form['actions'] = ['#type' => 'actions'];
69     $form['actions']['submit'] = ['#type' => 'submit', '#value' => 'Submit'];
70     return $form;
71   }
72
73   /**
74    * {@inheritdoc}
75    */
76   public function elementValidateRequired($element, FormStateInterface $form_state) {
77     // Set a custom validation error on the #required element.
78     if (!empty($element['#required_but_empty']) && isset($element['#form_test_required_error'])) {
79       $form_state->setError($element, $element['#form_test_required_error']);
80     }
81   }
82
83   /**
84    * {@inheritdoc}
85    */
86   public function submitForm(array &$form, FormStateInterface $form_state) {
87     $this->messenger()->addStatus('The form_test_validate_required_form form was submitted successfully.');
88   }
89
90 }