View source
<?php
namespace Drupal\form_api_example\Form;
use Drupal\Core\Form\FormStateInterface;
class AjaxAddMore extends DemoBase {
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.'),
];
$num_names = $form_state
->get('num_names');
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 ($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;
}
public function getFormId() {
return 'form_api_example_ajax_addmore';
}
public function addmoreCallback(array &$form, FormStateInterface $form_state) {
return $form['names_fieldset'];
}
public function addOne(array &$form, FormStateInterface $form_state) {
$name_field = $form_state
->get('num_names');
$add_button = $name_field + 1;
$form_state
->set('num_names', $add_button);
$form_state
->setRebuild();
}
public function removeCallback(array &$form, FormStateInterface $form_state) {
$name_field = $form_state
->get('num_names');
if ($name_field > 1) {
$remove_button = $name_field - 1;
$form_state
->set('num_names', $remove_button);
}
$form_state
->setRebuild();
}
public function submitForm(array &$form, FormStateInterface $form_state) {
$values = $form_state
->getValue([
'names_fieldset',
'name',
]);
$output = $this
->t('These people are coming to the picnic: @names', [
'@names' => implode(', ', $values),
]);
$this
->messenger()
->addMessage($output);
}
}