Skip to main content
2 of 2
extended the answer to show how the question code should be rewritten; Post Made Community Wiki
avpaderno
  • 97.9k
  • 15
  • 164
  • 284

Use FormStateInterface::setValueForElement(), which requires two arguments: the form element and the new value.

In your case, you would need to use code similar to the following one.

public function validateForm(array &$form, FormStateInterface $form_state) {
  $values = $form_state->getValues();
  if ($values['myfield'] != 'something') {
    $form_state->setValueForElement($form['myfield'], '');
    $form_state->setErrorByName('myfield', $this->t('Sorry, this field value is not correct.'));
  }
}
alberto56
  • 234
  • 1
  • 11