This form consists of 1 textfield, and 1 ajax button.
I'm trying to make it add another text field with each click.
It works for the first one, to get a total of 2 text fields. I cannot get more than 2 to appear though.
I suspect the dom is being updated, but not the form. So the subsequent callbacks add an element based on the original form build.
I'm not sure how to approach this in Drupal 8. Any insight would be appreciated.
Here is my form control
<?php
...
class MyModuleForm extends FormBase {
...
public function buildForm(array $form, array &$form_state) {
$form['foo'] = array(
'#type' => 'container',
'#tree' => TRUE,
'#prefix' => '<div id="foo-replace">',
'#suffix' => '</div>'
);
$form['foo'][0] = array(
'#type' => 'textfield'
);
$form['add'] = array(
'#type' => 'submit',
'#name' => 'add',
'#value' => t('Add'),
'#ajax' => array(
'callback' => array($this, 'addMore'),
'wrapper' => 'foo-replace',
'effect' => 'fade',
),
);
return $form;
}
public function addMore(array $form, array &$form_state) {
$form['foo'][] = array(
'#type' => 'textfield'
);
return $form['foo'];
}
}