3 namespace Drupal\form_test\Form;
5 use Drupal\Core\Form\FormBase;
6 use Drupal\Core\Form\FormStateInterface;
7 use Drupal\form_test\Callbacks;
10 * Form builder for testing \Drupal\Core\Form\FormValidatorInterface::validateForm().
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.
23 class FormTestValidateForm extends FormBase {
28 public function getFormId() {
29 return 'form_test_validate_form';
35 public function buildForm(array $form, FormStateInterface $form_state) {
36 $object = new Callbacks();
39 '#type' => 'textfield',
41 '#default_value' => '',
42 '#element_validate' => [[$object, 'validateName']],
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')]));
64 // Trigger a form validation error to see our changes.
65 $form_state->setErrorByName('');
67 // To simplify this test, enable form caching and use form storage to
68 // remember our alteration.
69 $form_state->setCached();
76 public function submitForm(array &$form, FormStateInterface $form_state) {