Drupal - Clear form fields after AJAX submit

You are looking for https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21Form%21FormStateInterface.php/function/FormStateInterface%3A%3AsetUserInput/8.2.x.

The values are the validated input, for setting the default values, the form system respects the original user input, which you can change with the method above.

However, for entity forms, it is a bit more complicated. $this->entity is a reference to the entity, you will still have that and it will fallback to that. What you probably need to do is create a new entity in save, assign it to $this->entity, then empty user input and $form_state->setRebuild(). That should then rebuild the form with a new and empty entity.


@Berdir's answer helped me to figure out the solution. We should indeed clear the user input, but we can not simply just say $form_state->setUserInput([]), because there are some system values, that should stay(e.g. form_id, form_token, _triggering_element_name, etc.).

I have created a custom method for it:

  /**
   * Clears form input.
   *
   * @param array $form
   *   The form.
   * @param \Drupal\Core\Form\FormStateInterface $form_state
   *   The form state.
   */
  protected function clearFormInput(array $form, FormStateInterface $form_state) {
    // Replace the form entity with an empty instance.
    $this->entity = $this->entityTypeManager->getStorage('my_entity_type')->create([]);
    // Clear user input.
    $input = $form_state->getUserInput();
    // We should not clear the system items from the user input.
    $clean_keys = $form_state->getCleanValueKeys();
    $clean_keys[] = 'ajax_page_state';
    foreach ($input as $key => $item) {
      if (!in_array($key, $clean_keys) && substr($key, 0, 1) !== '_') {
        unset($input[$key]);
      }
    }
    $form_state->setUserInput($input);
    // Rebuild the form state values.
    $form_state->setRebuild();
    $form_state->setStorage([]);
  }

I am calling $this->clearFormInput($form, $form_state); in the MymoduleForm::save() method(the very last step of the submission).

Tags:

Forms

Ajax

8