You are here

public static function EntityReferenceBrowserWidget::removeItemSubmit in Entity Browser 8

Same name and namespace in other branches
  1. 8.2 src/Plugin/Field/FieldWidget/EntityReferenceBrowserWidget.php \Drupal\entity_browser\Plugin\Field\FieldWidget\EntityReferenceBrowserWidget::removeItemSubmit()

Submit callback for remove buttons.

File

src/Plugin/Field/FieldWidget/EntityReferenceBrowserWidget.php, line 526

Class

EntityReferenceBrowserWidget
Plugin implementation of the 'entity_reference' widget for entity browser.

Namespace

Drupal\entity_browser\Plugin\Field\FieldWidget

Code

public static function removeItemSubmit(&$form, FormStateInterface $form_state) {
  $triggering_element = $form_state
    ->getTriggeringElement();
  if (!empty($triggering_element['#attributes']['data-entity-id']) && isset($triggering_element['#attributes']['data-row-id'])) {
    $id = $triggering_element['#attributes']['data-entity-id'];
    $row_id = $triggering_element['#attributes']['data-row-id'];
    $parents = array_slice($triggering_element['#parents'], 0, -static::$deleteDepth);
    $array_parents = array_slice($triggering_element['#array_parents'], 0, -static::$deleteDepth);

    // Find and remove correct entity.
    $values = explode(' ', $form_state
      ->getValue(array_merge($parents, [
      'target_id',
    ])));
    foreach ($values as $index => $item) {

      // @todo add weight field.
      if ($item == $id) {
        array_splice($values, $index, 1);
        break;
      }
    }
    $target_id_value = implode(' ', $values);

    // Set new value for this widget.
    $target_id_element =& NestedArray::getValue($form, array_merge($array_parents, [
      'target_id',
    ]));
    $form_state
      ->setValueForElement($target_id_element, $target_id_value);
    NestedArray::setValue($form_state
      ->getUserInput(), $target_id_element['#parents'], $target_id_value);

    // Rebuild form.
    $form_state
      ->setRebuild();
  }
}