Custom #ajax "Add another" button only adds 1 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

&lt;?php
...
class MyModuleForm extends FormBase {
  ...
  public function buildForm(array $form, array &amp;$form_state) {
    $form['foo'] = array(
      '#type' =&gt; 'container',
      '#tree' =&gt; TRUE,
      '#prefix' =&gt; '&lt;div id="foo-replace"&gt;',
      '#suffix' =&gt; '&lt;/div&gt;'
    );
    $form['foo'][0] = array(
      '#type' =&gt; 'textfield'
    );
    $form['add'] = array(
      '#type' =&gt; 'submit',
      '#name' =&gt; 'add',
      '#value' =&gt; t('Add'),
      '#ajax' =&gt; array(
        'callback' =&gt; array($this, 'addMore'),
        'wrapper' =&gt; 'foo-replace',
        'effect' =&gt; 'fade',
      ),
    );
    return $form;
  }

  public function addMore(array $form, array &amp;$form_state) {
    $form['foo'][] = array(
      '#type' =&gt; 'textfield'
    );
    return $form['foo'];
  }
}
You made a common mistake. In Form API, ['#ajax']['callback'] has only 2 purposes:


Make one-time changes to form, that are not meant to persist form reload, submit or second Ajax request. Good example is adding some classes to freshly modified element.
Return proper part of the form.


To have persistent changes, you need to keep the number of elements you want somewhere, for example in $form_state, and add them in form builder function, buildForm in your case. 

My approach would be to check $form_state['triggering_element'] to see if it was your Ajax button to invoke form building, and if so, increase counter. Then simply for($i = 0; $i &lt; $element_counter; ++$i) to add required number of elements.