Set form value to empty on validation fail I have a requirement to set a single field to empty, if it fails validation. The form is built using Drupal 8's Form API.

In my validateForm() function, I have the following:

public function validateForm(array &amp;$form, FormStateInterface $form_state) {
  $values = $form_state-&gt;getValues();
  if($values['myfield']!='something') {
     $form_state-&gt;setValue('myfield', '');
     $form_state-&gt;setErrorByName('myfield', $this-&gt;t('Sorry, this field value is not correct.'));
  }
}


Unfortunately, the above has no effect - when the form is rebuilt myfield still contains the user submitted value. 

I assume this is something to do with the order in which these functions are called? Or perhaps, because $form_state is not passed by reference? (I cannot do this, as it's then no longer compatible with the FormBase class I'm extending).



One solution I've found is to access the form element from the $form array in my validateForm() function:

$form['myfield']['#value'] = '';


But the above doesn't really feel like the correct solution?
Use setValueForElement:

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