class AjaxAddRemoveElements

Same name in other branches
  1. 4.0.x modules/form_api_example/src/Form/AjaxAddRemoveElements.php \Drupal\form_api_example\Form\AjaxAddRemoveElements

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

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\Form
View 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

Title Sort descending Modifiers Object type Summary Overriden Title Overrides
AjaxAddRemoveElements::addmoreCallback public function Callback for both ajax-enabled buttons.
AjaxAddRemoveElements::addOne public function Submit handler for the &quot;add-one-more&quot; button.
AjaxAddRemoveElements::buildForm public function Form with &#039;add more&#039; and &#039;remove&#039; buttons. Overrides FormInterface::buildForm
AjaxAddRemoveElements::getFormId public function Required by FormBase. Overrides FormInterface::getFormId
AjaxAddRemoveElements::removeCallback public function Submit handler for the &quot;remove&quot; button.
AjaxAddRemoveElements::submitForm public function Required by FormBase. Overrides FormInterface::submitForm
AjaxAddRemoveElements::validateForm public function Required by FormBase. Overrides FormBase::validateForm
DependencySerializationTrait::$_entityStorages protected property
DependencySerializationTrait::$_serviceIds protected property
DependencySerializationTrait::__sleep public function 1
DependencySerializationTrait::__wakeup public function 2
FormBase::$configFactory protected property The config factory. 3
FormBase::$requestStack protected property The request stack. 1
FormBase::$routeMatch protected property The route match.
FormBase::config protected function Retrieves a configuration object.
FormBase::configFactory protected function Gets the config factory for this form. 3
FormBase::container private function Returns the service container.
FormBase::create public static function Instantiates a new instance of this class. Overrides ContainerInjectionInterface::create 105
FormBase::currentUser protected function Gets the current user.
FormBase::getRequest protected function Gets the request object.
FormBase::getRouteMatch protected function Gets the route match.
FormBase::logger protected function Gets the logger for a specific channel.
FormBase::redirect protected function Returns a redirect response object for the specified route.
FormBase::resetConfigFactory public function Resets the configuration factory.
FormBase::setConfigFactory public function Sets the config factory for this form.
FormBase::setRequestStack public function Sets the request stack object to use.
LoggerChannelTrait::$loggerFactory protected property The logger channel factory service.
LoggerChannelTrait::getLogger protected function Gets the logger for a specific channel.
LoggerChannelTrait::setLoggerFactory public function Injects the logger channel factory.
MessengerTrait::$messenger protected property The messenger. 17
MessengerTrait::messenger public function Gets the messenger. 17
MessengerTrait::setMessenger public function Sets the messenger.
RedirectDestinationTrait::$redirectDestination protected property The redirect destination service. 1
RedirectDestinationTrait::getDestinationArray protected function Prepares a &#039;destination&#039; URL query parameter for use with \Drupal\Core\Url.
RedirectDestinationTrait::getRedirectDestination protected function Returns the redirect destination service.
RedirectDestinationTrait::setRedirectDestination public function Sets the redirect destination service.
StringTranslationTrait::$stringTranslation protected property The string translation service. 3
StringTranslationTrait::formatPlural protected function Formats a string containing a count of items.
StringTranslationTrait::getNumberOfPlurals protected function Returns the number of plurals supported by a given language.
StringTranslationTrait::getStringTranslation protected function Gets the string translation service.
StringTranslationTrait::setStringTranslation public function Sets the string translation service to use. 2
StringTranslationTrait::t protected function Translates a string to the current language or to a given language.