summaryrefslogtreecommitdiffstats
path: root/core/modules/system/tests/modules/form_test/src/Form/FormTestValidateRequiredForm.php
blob: 91be7b1e7fca709faeebb45c1b6b3c5a3f633652 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
<?php

namespace Drupal\form_test\Form;

use Drupal\Core\Form\FormBase;
use Drupal\Core\Form\FormStateInterface;

/**
 * Form constructor to test the #required property.
 *
 * @internal
 */
class FormTestValidateRequiredForm extends FormBase {

  /**
   * {@inheritdoc}
   */
  public function getFormId() {
    return 'form_test_validate_required_form';
  }

  /**
   * {@inheritdoc}
   */
  public function buildForm(array $form, FormStateInterface $form_state) {
    $options = ['foo' => 'foo', 'bar' => 'bar'];
    $validate = ['::elementValidateRequired'];

    $form['textfield'] = [
      '#type' => 'textfield',
      '#title' => 'Name',
      '#required' => TRUE,
      '#required_error' => t('Please enter a name.'),
    ];
    $form['checkboxes'] = [
      '#type' => 'checkboxes',
      '#title' => 'Checkboxes',
      '#options' => $options,
      '#required' => TRUE,
      '#form_test_required_error' => t('Please choose at least one option.'),
      '#element_validate' => $validate,
    ];
    $form['select'] = [
      '#type' => 'select',
      '#title' => 'Select',
      '#options' => $options,
      '#required' => TRUE,
      '#form_test_required_error' => t('Please select something.'),
      '#element_validate' => $validate,
    ];
    $form['radios'] = [
      '#type' => 'radios',
      '#title' => 'Radios',
      '#options' => $options,
      '#required' => TRUE,
    ];
    $form['radios_optional'] = [
      '#type' => 'radios',
      '#title' => 'Radios (optional)',
      '#options' => $options,
    ];
    $form['radios_optional_default_value_false'] = [
      '#type' => 'radios',
      '#title' => 'Radios (optional, with a default value of FALSE)',
      '#options' => $options,
      '#default_value' => FALSE,
    ];
    $form['actions'] = ['#type' => 'actions'];
    $form['actions']['submit'] = ['#type' => 'submit', '#value' => 'Submit'];
    return $form;
  }

  /**
   * {@inheritdoc}
   */
  public function elementValidateRequired($element, FormStateInterface $form_state) {
    // Set a custom validation error on the #required element.
    if (!empty($element['#required_but_empty']) && isset($element['#form_test_required_error'])) {
      $form_state->setError($element, $element['#form_test_required_error']);
    }
  }

  /**
   * {@inheritdoc}
   */
  public function submitForm(array &$form, FormStateInterface $form_state) {
    $this->messenger()->addStatus('The form_test_validate_required_form form was submitted successfully.');
  }

}