Skip to main content
2 of 6
added 33 characters in body
Coder1
  • 510
  • 7
  • 17

AJAX "Add another" type implementation 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 callback is just adding a field to the original $form, without taking account any updates since the form originally loaded.

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'];
  }
}
Coder1
  • 510
  • 7
  • 17