Given:
- I am using Drupal 8.
- I have a custom “add form” of the custom entity type.
- Form has an ajax submission.
Problem:
- When I submit form all the values remain in fields.
Expected:
- Form fields should be cleared after submission.
Form source code:
<?php namespace DrupalmymoduleForm; use DrupalCoreEntityContentEntityForm; use DrupalCoreFormFormStateInterface; /** * Form controller for the add/edit entity forms. */ class MymoduleForm extends ContentEntityForm { /** * {@inheritdoc} */ public function buildForm(array $form, FormStateInterface $form_state) { $form = parent::buildForm($form, $form_state); $form['#prefix'] = "<div id="{$this->getFormId()}-wrapper">"; $form['#suffix'] = '</div>'; $form['actions']['submit']['#ajax'] = [ 'wrapper' => $this->getFormId() . '-wrapper', 'callback' => array($this, 'ajaxRebuildCallback'), 'effect' => 'fade', ]; return $form; } /** * Callback for ajax form submission. * * @param array $form * An associative array containing the structure of the form. * @param DrupalCoreFormFormStateInterface $form_state * The current state of the form. * * @return array * The rebuilt form. */ public function ajaxRebuildCallback(array $form, FormStateInterface $form_state) { drupal_set_message(t('Entity was successfully created')); // @todo Clear form values. //$form_state->setRebuild(TRUE); //$form_state->setValues([]); /*$entity = Drupal::entityTypeManager()->getStorage('liveblog_post')->create([]); $form_object = Drupal::entityTypeManager() ->getFormObject('liveblog_post', 'add') ->setEntity($entity);*/ //$new_form_state = new FormState(); //$form = Drupal::formBuilder()->rebuildForm($this->getFormId(), $form_state); return $form; } /** * {@inheritdoc} */ public function save(array $form, FormStateInterface $form_state) { $entity = $this->getEntity(); $entity->save(); } }
P.S. you can find my attempts in the ajaxRebuildCallback()
method.
Sponsored by SupremePR