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?
Sponsored by SupremePR