Version 1
[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 class FormTestValidateForm extends FormBase {
22
23   /**
24    * {@inheritdoc}
25    */
26   public function getFormId() {
27     return 'form_test_validate_form';
28   }
29
30   /**
31    * {@inheritdoc}
32    */
33   public function buildForm(array $form, FormStateInterface $form_state) {
34     $object = new Callbacks();
35
36     $form['name'] = [
37       '#type' => 'textfield',
38       '#title' => 'Name',
39       '#default_value' => '',
40       '#element_validate' => [[$object, 'validateName']],
41     ];
42     $form['submit'] = [
43       '#type' => 'submit',
44       '#value' => 'Save',
45     ];
46
47     return $form;
48   }
49
50   /**
51    * {@inheritdoc}
52    */
53   public function validateForm(array &$form, FormStateInterface $form_state) {
54     if ($form_state->getValue('name') == 'validate') {
55       // Alter the form element.
56       $form['name']['#value'] = '#value changed by #validate';
57       // Alter the submitted value in $form_state.
58       $form_state->setValueForElement($form['name'], 'value changed by setValueForElement() in #validate');
59       // Output the element's value from $form_state.
60       drupal_set_message(t('@label value: @value', ['@label' => $form['name']['#title'], '@value' => $form_state->getValue('name')]));
61
62       // Trigger a form validation error to see our changes.
63       $form_state->setErrorByName('');
64
65       // To simplify this test, enable form caching and use form storage to
66       // remember our alteration.
67       $form_state->setCached();
68     }
69   }
70
71   /**
72    * {@inheritdoc}
73    */
74   public function submitForm(array &$form, FormStateInterface $form_state) {
75   }
76
77 }