function MediaLibraryWidget::addItems

Same name and namespace in other branches
  1. 9 core/modules/media_library/src/Plugin/Field/FieldWidget/MediaLibraryWidget.php \Drupal\media_library\Plugin\Field\FieldWidget\MediaLibraryWidget::addItems()
  2. 8.9.x core/modules/media_library/src/Plugin/Field/FieldWidget/MediaLibraryWidget.php \Drupal\media_library\Plugin\Field\FieldWidget\MediaLibraryWidget::addItems()
  3. 10 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 877

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) {
    // During the form rebuild, formElement() will create field item widget
    // elements using re-indexed deltas, so clear out FormState::$input to
    // avoid a mismatch between old and new deltas. The rebuilt elements will
    // have #default_value set appropriately for the current state of the field,
    // so nothing is lost in doing this.
    // @see Drupal\media_library\Plugin\Field\FieldWidget\MediaLibraryWidget::extractFormValues
    $button = $form_state->getTriggeringElement();
    $parents = array_slice($button['#parents'], 0, -1);
    $parents[] = 'selection';
    NestedArray::setValue($form_state->getUserInput(), $parents, NULL);
    $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();
}

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