7123aceef1a8736375a82551075a5c0a93eef792
[yaffs-website] / web / core / modules / system / tests / modules / form_test / src / Form / FormTestValidateForm.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 Drupal\form_test\Callbacks;
8
9 /**
10  * Form builder for testing \Drupal\Core\Form\FormValidatorInterface::validateForm().
11  *
12  * Serves for testing form processing and alterations by form validation
13  * handlers, especially for the case of a validation error:
14  * - $form_state->setValueForElement() should be able to alter submitted values
15  *   in $form_state->getValues() without affecting the form element.
16  * - #element_validate handlers should be able to alter the $element in the form
17  *   structure and the alterations should be contained in the rebuilt form.
18  * - #validate handlers should be able to alter the $form and the alterations
19  *   should be contained in the rebuilt form.
20  *
21  * @internal
22  */
23 class FormTestValidateForm extends FormBase {
24
25   /**
26    * {@inheritdoc}
27    */
28   public function getFormId() {
29     return 'form_test_validate_form';
30   }
31
32   /**
33    * {@inheritdoc}
34    */
35   public function buildForm(array $form, FormStateInterface $form_state) {
36     $object = new Callbacks();
37
38     $form['name'] = [
39       '#type' => 'textfield',
40       '#title' => 'Name',
41       '#default_value' => '',
42       '#element_validate' => [[$object, 'validateName']],
43     ];
44     $form['submit'] = [
45       '#type' => 'submit',
46       '#value' => 'Save',
47     ];
48
49     return $form;
50   }
51
52   /**
53    * {@inheritdoc}
54    */
55   public function validateForm(array &$form, FormStateInterface $form_state) {
56     if ($form_state->getValue('name') == 'validate') {
57       // Alter the form element.
58       $form['name']['#value'] = '#value changed by #validate';
59       // Alter the submitted value in $form_state.
60       $form_state->setValueForElement($form['name'], 'value changed by setValueForElement() in #validate');
61       // Output the element's value from $form_state.
62       drupal_set_message(t('@label value: @value', ['@label' => $form['name']['#title'], '@value' => $form_state->getValue('name')]));
63
64       // Trigger a form validation error to see our changes.
65       $form_state->setErrorByName('');
66
67       // To simplify this test, enable form caching and use form storage to
68       // remember our alteration.
69       $form_state->setCached();
70     }
71   }
72
73   /**
74    * {@inheritdoc}
75    */
76   public function submitForm(array &$form, FormStateInterface $form_state) {
77   }
78
79 }