function AddFormBase::updateLibrary

Same name in other branches
  1. 9 core/modules/media_library/src/Form/AddFormBase.php \Drupal\media_library\Form\AddFormBase::updateLibrary()
  2. 8.9.x core/modules/media_library/src/Form/AddFormBase.php \Drupal\media_library\Form\AddFormBase::updateLibrary()
  3. 11.x core/modules/media_library/src/Form/AddFormBase.php \Drupal\media_library\Form\AddFormBase::updateLibrary()

AJAX callback to send the new media item(s) to the media library.

Parameters

array $form: The complete form.

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

Return value

array|\Drupal\Core\Ajax\AjaxResponse The form array if there are validation errors, or an AJAX response to add the created items to the current selection.

1 call to AddFormBase::updateLibrary()
AddFormBase::updateWidget in core/modules/media_library/src/Form/AddFormBase.php
AJAX callback to send the new media item(s) to the calling code.

File

core/modules/media_library/src/Form/AddFormBase.php, line 695

Class

AddFormBase
Provides a base class for creating media items from within the media library.

Namespace

Drupal\media_library\Form

Code

public function updateLibrary(array &$form, FormStateInterface $form_state) {
    if ($form_state::hasAnyErrors()) {
        return $form;
    }
    $media_ids = array_map(function (MediaInterface $media) {
        return $media->id();
    }, $this->getAddedMediaItems($form_state));
    $selected_count = $this->getSelectedMediaItemCount($media_ids, $form_state);
    $response = new AjaxResponse();
    $response->addCommand(new UpdateSelectionCommand($media_ids));
    $media_id_to_focus = array_pop($media_ids);
    $response->addCommand(new ReplaceCommand('#media-library-add-form-wrapper', $this->buildMediaLibraryUi($form_state)));
    $response->addCommand(new InvokeCommand("#media-library-content [value={$media_id_to_focus}]", 'focus'));
    $available_slots = $this->getMediaLibraryState($form_state)
        ->getAvailableSlots();
    if ($available_slots > 0 && $selected_count > $available_slots) {
        $warning = $this->formatPlural($selected_count - $available_slots, 'There are currently @total items selected. The maximum number of items for the field is @max. Remove @count item from the selection.', 'There are currently @total items selected. The maximum number of items for the field is @max. Remove @count items from the selection.', [
            '@total' => $selected_count,
            '@max' => $available_slots,
        ]);
        $response->addCommand(new MessageCommand($warning, '#media-library-messages', [
            'type' => 'warning',
        ]));
    }
    return $response;
}

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