function AjaxAddMore::buildForm

Same name in other branches
  1. 3.x modules/form_api_example/src/Form/AjaxAddMore.php \Drupal\form_api_example\Form\AjaxAddMore::buildForm()
  2. 4.0.x modules/form_api_example/src/Form/AjaxAddMore.php \Drupal\form_api_example\Form\AjaxAddMore::buildForm()

Form with 'add more' and 'remove' buttons.

This example shows a button to "add more" - add another textfield, and the corresponding "remove" button.

File

form_api_example/src/Form/AjaxAddMore.php, line 24

Class

AjaxAddMore
Implements the ajax demo form controller.

Namespace

Drupal\form_api_example\Form

Code

public function buildForm(array $form, FormStateInterface $form_state) {
    $form['description'] = [
        '#type' => 'item',
        '#markup' => $this->t('This example shows an add-more and a remove-last button.'),
    ];
    // Gather the number of names in the form already.
    $num_names = $form_state->get('num_names');
    // We have to ensure that there is at least one name field.
    if ($num_names === NULL) {
        $name_field = $form_state->set('num_names', 1);
        $num_names = 1;
    }
    $form['#tree'] = TRUE;
    $form['names_fieldset'] = [
        '#type' => 'fieldset',
        '#title' => $this->t('People coming to picnic'),
        '#prefix' => '<div id="names-fieldset-wrapper">',
        '#suffix' => '</div>',
    ];
    for ($i = 0; $i < $num_names; $i++) {
        $form['names_fieldset']['name'][$i] = [
            '#type' => 'textfield',
            '#title' => $this->t('Name'),
        ];
    }
    $form['names_fieldset']['actions'] = [
        '#type' => 'actions',
    ];
    $form['names_fieldset']['actions']['add_name'] = [
        '#type' => 'submit',
        '#value' => $this->t('Add one more'),
        '#submit' => [
            '::addOne',
        ],
        '#ajax' => [
            'callback' => '::addmoreCallback',
            'wrapper' => 'names-fieldset-wrapper',
        ],
    ];
    // If there is more than one name, add the remove button.
    if ($num_names > 1) {
        $form['names_fieldset']['actions']['remove_name'] = [
            '#type' => 'submit',
            '#value' => $this->t('Remove one'),
            '#submit' => [
                '::removeCallback',
            ],
            '#ajax' => [
                'callback' => '::addmoreCallback',
                'wrapper' => 'names-fieldset-wrapper',
            ],
        ];
    }
    $form['actions']['submit'] = [
        '#type' => 'submit',
        '#value' => $this->t('Submit'),
    ];
    return $form;
}