You are here

public function FormTestValidateForm::validateForm in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/system/tests/modules/form_test/src/Form/FormTestValidateForm.php \Drupal\form_test\Form\FormTestValidateForm::validateForm()

Form validation handler.

Parameters

array $form: An associative array containing the structure of the form.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

Overrides FormBase::validateForm

File

core/modules/system/tests/modules/form_test/src/Form/FormTestValidateForm.php, line 55

Class

FormTestValidateForm
Form builder for testing \Drupal\Core\Form\FormValidatorInterface::validateForm().

Namespace

Drupal\form_test\Form

Code

public function validateForm(array &$form, FormStateInterface $form_state) {
  if ($form_state
    ->getValue('name') == 'validate') {

    // Alter the form element.
    $form['name']['#value'] = '#value changed by #validate';

    // Alter the submitted value in $form_state.
    $form_state
      ->setValueForElement($form['name'], 'value changed by setValueForElement() in #validate');

    // Output the element's value from $form_state.
    $this
      ->messenger()
      ->addStatus($this
      ->t('@label value: @value', [
      '@label' => $form['name']['#title'],
      '@value' => $form_state
        ->getValue('name'),
    ]));

    // Trigger a form validation error to see our changes.
    $form_state
      ->setErrorByName('');

    // To simplify this test, enable form caching and use form storage to
    // remember our alteration.
    $form_state
      ->setCached();
  }
}