6

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 &$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.'));
  }
}

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?

3
  • This is just fine, here is some extra info on what the $form_state is and why it's used. – Fons Vandamme Jan 12 '17 at 10:36
  • 3
    As for $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 as FormStateInterface &$form_state. – kiamlaluno Jan 12 '17 at 10:42
  • So, why does $form_state->setValue('myfield', ''); not have the desired effect? It seems like it should. – user34185 Jan 12 '17 at 12:22
3

Use setValueForElement:

$new_value = '';
$form_state->setValueForElement($form['myfield'], $new_value);
1
  • this worked for me – leandro713 Feb 26 '19 at 16:04
2

In your validateForm you can use:

 public function validateForm(array &$form, FormStateInterface $form_state) {

    if($form_state->getValue('myfield')!='something') {

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

        $form_state->setErrorByName('myfield', t('Sorry, this field value is not correct.'));
    }

  }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy