I need to set the value of a form element to an empty string, when it doesn't pass validation.
I tried using the following code, but the form element still contains the last submitted value, when the form is re-built.
public function validateForm(array &$form, FormStateInterface $form_state) {
$values = $form_state->getValues();
if ($values['myfield'] != 'something') {
$form_state->setValue('myfield', '');
$form_state->setErrorByName('myfield', $this->t('Sorry, this field value is not correct.'));
}
}
A workaround I found is using the following code.
public function validateForm(array &$form, FormStateInterface $form_state) {
$values = $form_state->getValues();
if ($values['myfield'] != 'something') {
$form['myfield']['#value'] = '';
$form_state->setErrorByName('myfield', $this->t('Sorry, this field value is not correct.'));
}
}
Instead of calling $form_state->setValue('myfield', '')
, it sets the value of #value
in the $form
array.
It doesn't seem the correct solution, though. How can I achieve what I want?
$form_state
passed as reference: in PHP 5, objects are automatically passed by reference, without the need to declare the argument as passed as reference. Since Drupal 8 requires PHP 5, you will not see the hook argument declared asFormStateInterface &$form_state
.