4

I've got a form that submits via AJAX and in the callback I need to rebuild certain parts of the page to reflect the newly submitted data. One of these parts is the form, which I need to clear all user input values from so it's ready to use again.

$response = new AjaxResponse();

// Remove all user submitted values
$form_state->setValues( array() );
$form_state->setRebuild( TRUE );

// Build a new instance of the form
$form_object = \Drupal::service('class_resolver')->getInstanceFromDefinition('Drupal\tpl_project\Form\MultiContactForm');
$form_object->setCompany( $company );
$replacement_form = \Drupal::formBuilder()->buildForm( $form_object, $form_state );

// Replace the old form with the new one
$response->addCommand(new HTMLCommand('.form-container', $replacement_form));

return $response;

When the form is submitted it runs the validation callback, the submit handler, then calls the above ajax handler. When it rebuilds the form in the above process, it fires the validation and submit handles again, thus storing two records.

How can I prevent this from happening and still rebuild the form to display no user input all within the same request?

Any help greatly appreciated.

1 Answer 1

0

See if this will help: How can I implement AJAX form submission?

It's a pretty decent checklist for ajax form operations.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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