function ListItemBase::deleteSubmit

Same name and namespace in other branches
  1. 10 core/modules/options/src/Plugin/Field/FieldType/ListItemBase.php \Drupal\options\Plugin\Field\FieldType\ListItemBase::deleteSubmit()

Deletes a row/option.

Parameters

array $form: The form array to add elements to.

\Drupal\Core\Form\FormStateInterface $form_state: The current state of the form.

File

core/modules/options/src/Plugin/Field/FieldType/ListItemBase.php, line 296

Class

ListItemBase
Plugin base class inherited by the options field types.

Namespace

Drupal\options\Plugin\Field\FieldType

Code

public static function deleteSubmit(array $form, FormStateInterface $form_state) {
  $allowed_values = $form_state->getStorage()['allowed_values'];
  $button = $form_state->getTriggeringElement();
  $element = NestedArray::getValue($form, array_slice($button['#array_parents'], 0, -1));
  $item_to_be_removed = $element['item']['label']['#default_value'];
  $remaining_allowed_values = array_diff($allowed_values, [
    $item_to_be_removed,
  ]);
  $form_state->set('allowed_values', $remaining_allowed_values);
  // The user input is directly modified to preserve the rest of the data on
  // the page as it cannot be rebuilt from a fresh form state.
  $user_input = $form_state->getUserInput();
  NestedArray::unsetValue($user_input, $element['#parents']);
  // Reset the keys in the array.
  $table_parents = $element['#parents'];
  array_pop($table_parents);
  $new_values = array_values(NestedArray::getValue($user_input, $table_parents));
  NestedArray::setValue($user_input, $table_parents, $new_values);
  $form_state->setUserInput($user_input);
  $form_state->set('items_count', $form_state->get('items_count') - 1);
  $form_state->setRebuild();
}

Buggy or inaccurate documentation? Please file an issue. Need support? Need help programming? Connect with the Drupal community.