class AjaxAddRemoveElements in Examples for Developers 3.x
Example ajax add remove buttons.
This example demonstrates using ajax callbacks to add people's names to a list of picnic attendees with an option to remove specific people.
Hierarchy
- class \Drupal\Core\Form\FormBase implements ContainerInjectionInterface, FormInterface uses DependencySerializationTrait, LoggerChannelTrait, MessengerTrait, RedirectDestinationTrait, StringTranslationTrait
- class \Drupal\form_api_example\Form\AjaxAddRemoveElements
Expanded class hierarchy of AjaxAddRemoveElements
1 string reference to 'AjaxAddRemoveElements'
- form_api_example.routing.yml in modules/
form_api_example/ form_api_example.routing.yml - modules/form_api_example/form_api_example.routing.yml
File
- modules/
form_api_example/ src/ Form/ AjaxAddRemoveElements.php, line 14
Namespace
Drupal\form_api_example\FormView source
class AjaxAddRemoveElements extends FormBase {
/**
* Required by FormBase.
*/
public function getFormId() {
return 'form_api_example_ajaxaddremoveelements';
}
/**
* Form with 'add more' and 'remove' buttons.
*/
public function buildForm(array $form, FormStateInterface $form_state) {
$form['description'] = [
'#type' => 'item',
'#markup' => $this
->t('This example shows an add-more button and a remove button for each specific element.'),
];
// Get the number of names in the form already.
$num_lines = $form_state
->get('num_lines');
// We have to ensure that there is at least one name field.
if ($num_lines === NULL) {
$form_state
->set('num_lines', 1);
$num_lines = $form_state
->get('num_lines');
}
// Get a list of fields that were removed.
$removed_fields = $form_state
->get('removed_fields');
// If no fields have been removed yet we use an empty array.
if ($removed_fields === NULL) {
$form_state
->set('removed_fields', []);
$removed_fields = $form_state
->get('removed_fields');
}
$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_lines; $i++) {
// Check if field was removed.
if (in_array($i, $removed_fields)) {
// Skip if field was removed and move to the next field.
continue;
}
/* Create a new fieldset for each person
* where we can add first and last name
*/
// Fieldset title.
$form['names_fieldset'][$i] = [
'#type' => 'fieldset',
'#title' => $this
->t('Person') . ' ' . ($i + 1),
];
// Date.
$form['names_fieldset'][$i]['firstname'] = [
'#type' => 'textfield',
'#title' => $this
->t('First name'),
];
// Amount.
$form['names_fieldset'][$i]['lastname'] = [
'#type' => 'textfield',
'#title' => $this
->t('Last name'),
];
$form['names_fieldset'][$i]['actions'] = [
'#type' => 'submit',
'#value' => $this
->t('Remove'),
'#name' => $i,
'#submit' => [
'::removeCallback',
],
'#ajax' => [
'callback' => '::addmoreCallback',
'wrapper' => 'names-fieldset-wrapper',
],
];
}
$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',
],
];
$form['actions']['submit'] = [
'#type' => 'submit',
'#value' => $this
->t('Submit'),
];
return $form;
}
/**
* Callback for both ajax-enabled buttons.
*
* Selects and returns the fieldset with the names in it.
*/
public function addmoreCallback(array &$form, FormStateInterface $form_state) {
return $form['names_fieldset'];
}
/**
* Submit handler for the "add-one-more" button.
*
* Increments the max counter and causes a rebuild.
*/
public function addOne(array &$form, FormStateInterface $form_state) {
$num_field = $form_state
->get('num_lines');
$add_button = $num_field + 1;
$form_state
->set('num_lines', $add_button);
$form_state
->setRebuild();
}
/**
* Submit handler for the "remove" button.
*
* Removes the corresponding line.
*/
public function removeCallback(array &$form, FormStateInterface $form_state) {
/*
* We use the name of the remove button to find
* the element we want to remove
* Line 72: '#name' => $i,.
*/
$trigger = $form_state
->getTriggeringElement();
$indexToRemove = $trigger['#name'];
// Remove the fieldset from $form (the easy way)
unset($form['names_fieldset'][$indexToRemove]);
// Remove the fieldset from $form_state (the hard way)
// First fetch the fieldset, then edit it, then set it again
// Form API does not allow us to directly edit the field.
$namesFieldset = $form_state
->getValue('names_fieldset');
unset($namesFieldset[$indexToRemove]);
// $form_state->unsetValue('names_fieldset');
$form_state
->setValue('names_fieldset', $namesFieldset);
// Keep track of removed fields so we can add new fields at the bottom
// Without this they would be added where a value was removed.
$removed_fields = $form_state
->get('removed_fields');
$removed_fields[] = $indexToRemove;
$form_state
->set('removed_fields', $removed_fields);
// Rebuild form_state.
$form_state
->setRebuild();
}
/**
* Required by FormBase.
*/
public function validateForm(array &$form, FormStateInterface $form_state) {
}
/**
* Required by FormBase.
*/
public function submitForm(array &$form, FormStateInterface $form_state) {
}
}
Members
Name | Modifiers | Type | Description | Overrides |
---|---|---|---|---|
AjaxAddRemoveElements:: |
public | function | Callback for both ajax-enabled buttons. | |
AjaxAddRemoveElements:: |
public | function | Submit handler for the "add-one-more" button. | |
AjaxAddRemoveElements:: |
public | function |
Form with 'add more' and 'remove' buttons. Overrides FormInterface:: |
|
AjaxAddRemoveElements:: |
public | function |
Required by FormBase. Overrides FormInterface:: |
|
AjaxAddRemoveElements:: |
public | function | Submit handler for the "remove" button. | |
AjaxAddRemoveElements:: |
public | function |
Required by FormBase. Overrides FormInterface:: |
|
AjaxAddRemoveElements:: |
public | function |
Required by FormBase. Overrides FormBase:: |
|
DependencySerializationTrait:: |
protected | property | ||
DependencySerializationTrait:: |
protected | property | ||
DependencySerializationTrait:: |
public | function | 2 | |
DependencySerializationTrait:: |
public | function | 2 | |
FormBase:: |
protected | property | The config factory. | 3 |
FormBase:: |
protected | property | The request stack. | 1 |
FormBase:: |
protected | property | The route match. | |
FormBase:: |
protected | function | Retrieves a configuration object. | |
FormBase:: |
protected | function | Gets the config factory for this form. | 3 |
FormBase:: |
private | function | Returns the service container. | |
FormBase:: |
public static | function |
Instantiates a new instance of this class. Overrides ContainerInjectionInterface:: |
105 |
FormBase:: |
protected | function | Gets the current user. | |
FormBase:: |
protected | function | Gets the request object. | |
FormBase:: |
protected | function | Gets the route match. | |
FormBase:: |
protected | function | Gets the logger for a specific channel. | |
FormBase:: |
protected | function | Returns a redirect response object for the specified route. | |
FormBase:: |
public | function | Resets the configuration factory. | |
FormBase:: |
public | function | Sets the config factory for this form. | |
FormBase:: |
public | function | Sets the request stack object to use. | |
LoggerChannelTrait:: |
protected | property | The logger channel factory service. | |
LoggerChannelTrait:: |
protected | function | Gets the logger for a specific channel. | |
LoggerChannelTrait:: |
public | function | Injects the logger channel factory. | |
MessengerTrait:: |
protected | property | The messenger. | 27 |
MessengerTrait:: |
public | function | Gets the messenger. | 27 |
MessengerTrait:: |
public | function | Sets the messenger. | |
RedirectDestinationTrait:: |
protected | property | The redirect destination service. | 1 |
RedirectDestinationTrait:: |
protected | function | Prepares a 'destination' URL query parameter for use with \Drupal\Core\Url. | |
RedirectDestinationTrait:: |
protected | function | Returns the redirect destination service. | |
RedirectDestinationTrait:: |
public | function | Sets the redirect destination service. | |
StringTranslationTrait:: |
protected | property | The string translation service. | 4 |
StringTranslationTrait:: |
protected | function | Formats a string containing a count of items. | |
StringTranslationTrait:: |
protected | function | Returns the number of plurals supported by a given language. | |
StringTranslationTrait:: |
protected | function | Gets the string translation service. | |
StringTranslationTrait:: |
public | function | Sets the string translation service to use. | 2 |
StringTranslationTrait:: |
protected | function | Translates a string to the current language or to a given language. |