3

I have a rather complex form validation depending on multiple fields. If validation fails, I would like to set the form values (of all or some explicit fields) to an empty value. This is what I tried, but none of the three approaches works:

public function validateForm(array &$form, FormStateInterface $form_state) {
  ...
  if (!$authorized) {

    $this->messenger->addError($this->t('An error occured.'));

    $form['name']['#value']=''; // approach 1

    $form_state->setValue('name',''); // approach 2

    $form_state->setValueForElement($form['name'], ''); // approach 3

    $form_state->setRebuild();
   }
 }
1

Have you looked at unsetValue()?

Example usage:

public function validateForm(array &$form, FormStateInterface $form_state) {
  ...
  if (!$authorized) {

    $this->messenger->addError($this->t('An error occurred.'));

    $form_state->unsetValue('name');

   }
 }

From the doc:

Removes a specific key from the submitted form values.

  • @param string|array $key
  • Values are stored as a multi-dimensional associative array. If $key is a string, it will use unset($values[$key]). If $key is an array, each element of the array will be used as a nested key. If $key = array('foo', 'bar') it will use unset($values['foo']['bar']).
| improve this answer | |
  • doesn't work, value is still displayed in the form field. – Miguel San Aug 15 '18 at 10:40
  • 1
    it seems that $form_state->setUserInput([]); does the trick. But I don't know how to use it to only empty certain form fields. When I use it like this the whole form gets empty. – Miguel San Aug 15 '18 at 10:58
  • Sorry, I misunderstood what you were trying to do. It takes an associative array of values: $form_state->setUserInput(['name' => '']); – mediaashley Aug 15 '18 at 11:18
  • I tried like this, but still it empties all values, not only name. – Miguel San Aug 15 '18 at 12:32
  • 2
    setUserInput() replaces all existing values. You need to get the user input with getUserInput(), unset the keys you want to have removed, then set it again. – Berdir Aug 15 '18 at 19:33
0

This does the trick for all the form fields:

 $form_state->setUserInput([]);

I think it should not be used for field validations but for error handling for example.

try {
  $res = $this->client->request('GET', '/demandes/' . $demandeId, [
    'headers' => ['Accept' => 'application/json'],
  ]);
  $demandeObject = Json::decode($res->getBody());
}
catch (ConnectException $e) {
  \Drupal::messenger()->addError(t("Une erreur est survenue: Le document n'a pas été ajouté. Veuillez contacter l'administrateur du site si le problème persiste."));
  // Rebuild form
  $form_state->setRebuild();
  // Reset all form fields
  $form_state->setUserInput([]);
}
| improve this answer | |

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.