function WidgetBase::deleteSubmit

Same name and namespace in other branches
  1. 11.x core/lib/Drupal/Core/Field/WidgetBase.php \Drupal\Core\Field\WidgetBase::deleteSubmit()

Ajax submit callback for the "Remove" button.

This re-numbers form elements and removes an item.

Parameters

array $form: The form array to remove elements from.

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

File

core/lib/Drupal/Core/Field/WidgetBase.php, line 379

Class

WidgetBase
Base class for 'Field widget' plugin implementations.

Namespace

Drupal\Core\Field

Code

public static function deleteSubmit(&$form, FormStateInterface $form_state) {
  $button = $form_state->getTriggeringElement();
  $delta = (int) $button['#delta'];
  $array_parents = array_slice($button['#array_parents'], 0, -4);
  $parent_element = NestedArray::getValue($form, array_merge($array_parents, [
    'widget',
  ]));
  $field_name = $parent_element['#field_name'];
  $parents = $parent_element['#field_parents'];
  $field_state = static::getWidgetState($parents, $field_name, $form_state);
  $user_input = $form_state->getUserInput();
  $field_input = NestedArray::getValue($user_input, $parent_element['#parents'], $exists);
  if ($exists) {
    $field_values = [];
    foreach ($field_input as $key => $input) {
      if (is_numeric($key) && $key >= $delta) {
        if ((int) $key === $delta) {
          --$key;
          continue;
        }
      }
      $field_values[$key] = $input;
    }
    NestedArray::setValue($user_input, $parent_element['#parents'], $field_values);
    $form_state->setUserInput($user_input);
  }
  $field_state['deleted_item'] = $delta;
  unset($parent_element[$delta]);
  NestedArray::setValue($form, $array_parents, $parent_element);
  if ($field_state['items_count'] > 0) {
    $field_state['items_count']--;
  }
  $user_input = $form_state->getUserInput();
  $input = NestedArray::getValue($user_input, $parent_element['#parents'], $exists);
  $weight = -1 * $field_state['items_count'];
  foreach ($input as $key => $item) {
    if ($item) {
      $input[$key]['_weight'] = $weight++;
    }
  }
  // Reset indices.
  $input = array_values($input);
  $user_input = $form_state->getUserInput();
  NestedArray::setValue($user_input, $parent_element['#parents'], $input);
  $form_state->setUserInput($user_input);
  static::setWidgetState($parents, $field_name, $form_state, $field_state);
  $form_state->setRebuild();
}

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