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

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

$new_value = '';
$form_state->setValueForElement($form['myfield'], $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.'));
  }
}

Use setValueForElement:

$new_value = '';
$form_state->setValueForElement($form['myfield'], $new_value);

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.'));
  }
}
Source Link
alberto56
  • 234
  • 1
  • 11

Use setValueForElement:

$new_value = '';
$form_state->setValueForElement($form['myfield'], $new_value);