I am trying to create a simple form in D8 that submits with a submit button and then replaces the entire form content via ajax.
For some reason, my AJAX submit works perfectly on the first click but then kicks in a normal submit handler.
This Works
public function getFormId() {
return 'my_form';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form['#prefix'] = '<div id="form-test">';
$form['#suffix'] = '</div>';
$form['title'] = array(
'#type' => 'textfield',
'#title' => t('Title'),
'#required' => TRUE,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit ').time(),
'#ajax' => [
'callback' => [$this, 'loadStep'],
'wrapper' => 'form-test',
'effect' => 'fade',
],
);
return $form;
}
public function loadStep(array &$form, FormStateInterface $form_state) {
$response = new AjaxResponse();
$form['submit']['#value'] = time();
$response->addCommand(new HtmlCommand('#form-test', $form));
return $response;
}
public function validateForm(array &$form, FormStateInterface $form_state) {
}
public function submitForm(array &$form, FormStateInterface $form_state) {
// TODO: Implement submitForm() method.
}
This Does NOT work
public function getFormId() {
return 'my_form';
}
public function buildForm(array $form, FormStateInterface $form_state) {
$form['#prefix'] = '<div id="form-test">';
$form['#suffix'] = '</div>';
$form['title'] = array(
'#type' => 'textfield',
'#title' => t('Title'),
'#required' => TRUE,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit ').time(),
'#ajax' => [
'callback' => [$this, 'loadStep'],
'wrapper' => 'form-test',
'effect' => 'fade',
],
);
return $form;
}
public function loadStep(array &$form, FormStateInterface $form_state) {
$response = new AjaxResponse();
$form['#prefix'] = '<div id="form-test">';
$form['#suffix'] = '</div>';
$form['title'] = array(
'#type' => 'textfield',
'#title' => t('Title'),
'#required' => TRUE,
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => t('Submit ').time(),
'#ajax' => [
'callback' => [$this, 'loadStep'],
'wrapper' => 'form-test',
'effect' => 'fade',
],
);
$response->addCommand(new HtmlCommand('#form-test', $form));
return $response;
}
public function validateForm(array &$form, FormStateInterface $form_state) {
}
public function submitForm(array &$form, FormStateInterface $form_state) {
// TODO: Implement submitForm() method.
}
It seem like as soon as I add something more substantially than just changing the label on the submit button, it seems to fail from the second submit where it just invokes a regular submit.
I want to replace the entire form on every submit (basically creating a multistep form).
I am running 8.3.2 btw
Many thanks for all help.