You are here

public static function MediaLibraryWidget::addItems in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/media_library/src/Plugin/Field/FieldWidget/MediaLibraryWidget.php \Drupal\media_library\Plugin\Field\FieldWidget\MediaLibraryWidget::addItems()

Updates the field state and flags the form for rebuild.

Parameters

array $form: The form array.

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

File

core/modules/media_library/src/Plugin/Field/FieldWidget/MediaLibraryWidget.php, line 845

Class

MediaLibraryWidget
Plugin implementation of the 'media_library_widget' widget.

Namespace

Drupal\media_library\Plugin\Field\FieldWidget

Code

public static function addItems(array $form, FormStateInterface $form_state) {
  $button = $form_state
    ->getTriggeringElement();
  $element = NestedArray::getValue($form, array_slice($button['#array_parents'], 0, -1));
  $field_state = static::getFieldState($element, $form_state);
  $media = static::getNewMediaItems($element, $form_state);
  if (!empty($media)) {

    // Get the weight of the last items and count from there.
    $last_element = end($field_state['items']);
    $weight = $last_element ? $last_element['weight'] : 0;
    foreach ($media as $media_item) {

      // Any ID can be passed to the widget, so we have to check access.
      if ($media_item
        ->access('view')) {
        $field_state['items'][] = [
          'target_id' => $media_item
            ->id(),
          'weight' => ++$weight,
        ];
      }
    }
    static::setFieldState($element, $form_state, $field_state);
  }
  $form_state
    ->setRebuild();
}