3 namespace Drupal\form_test\Form;
5 use Drupal\Core\Form\FormBase;
6 use Drupal\Core\Form\FormStateInterface;
9 * Form builder to test programmatic form submissions.
11 class FormTestProgrammaticForm extends FormBase {
16 public function getFormId() {
17 return 'form_test_programmatic_form';
23 public function buildForm(array $form, FormStateInterface $form_state) {
24 $form['textfield'] = [
25 '#title' => 'Textfield',
26 '#type' => 'textfield',
29 $form['checkboxes'] = [
30 '#title' => t('Checkboxes'),
31 '#type' => 'checkboxes',
33 1 => 'First checkbox',
34 2 => 'Second checkbox',
36 // Both checkboxes are selected by default so that we can test the ability
37 // of programmatic form submissions to uncheck them.
38 '#default_value' => [1, 2],
41 $form['field_to_validate'] = [
43 '#title' => 'Field to validate (in the case of limited validation)',
44 '#description' => 'If the form is submitted by clicking the "Submit with limited validation" button, then validation can be limited based on the value of this radio button.',
46 'all' => 'Validate all fields',
47 'textfield' => 'Validate the "Textfield" field',
48 'field_to_validate' => 'Validate the "Field to validate" field',
50 '#default_value' => 'all',
53 $form['field_restricted'] = [
54 '#type' => 'textfield',
55 '#title' => 'Textfield (no access)',
59 // The main submit button for the form.
64 // A secondary submit button that allows validation to be limited based on
65 // the value of the above radio selector.
66 $form['submit_limit_validation'] = [
68 '#value' => 'Submit with limited validation',
69 // Use the same submit handler for this button as for the form itself.
70 // (This must be set explicitly or otherwise the form API will ignore the
71 // #limit_validation_errors property.)
72 '#submit' => ['::submitForm'],
74 $user_input = $form_state->getUserInput();
75 if (!empty($user_input['field_to_validate']) && $user_input['field_to_validate'] != 'all') {
76 $form['submit_limit_validation']['#limit_validation_errors'] = [
77 [$user_input['field_to_validate']],
87 public function validateForm(array &$form, FormStateInterface $form_state) {
88 if ($form_state->isValueEmpty('textfield')) {
89 $form_state->setErrorByName('textfield', t('Textfield is required.'));
96 public function submitForm(array &$form, FormStateInterface $form_state) {
97 $form_state->set('programmatic_form_submit', $form_state->getValues());