6

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?

2
  • This is just fine, here is some extra info on what the $form_state is and why it's used. Commented Jan 12, 2017 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.
    – avpaderno
    Commented Jan 12, 2017 at 10:42

2 Answers 2

3

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.'));
  }
}
1
  • this worked for me
    – leandro713
    Commented Feb 26, 2019 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 and acknowledge you have read our privacy policy.