You are here

public function AjaxAddRemoveElements::removeCallback in Examples for Developers 3.x

Submit handler for the "remove" button.

Removes the corresponding line.

File

modules/form_api_example/src/Form/AjaxAddRemoveElements.php, line 143

Class

AjaxAddRemoveElements
Example ajax add remove buttons.

Namespace

Drupal\form_api_example\Form

Code

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();
}