function MediaLibrarySelectForm::updateWidget

Same name in other branches
  1. 9 core/modules/media_library/src/Plugin/views/field/MediaLibrarySelectForm.php \Drupal\media_library\Plugin\views\field\MediaLibrarySelectForm::updateWidget()
  2. 8.9.x core/modules/media_library/src/Plugin/views/field/MediaLibrarySelectForm.php \Drupal\media_library\Plugin\views\field\MediaLibrarySelectForm::updateWidget()
  3. 11.x core/modules/media_library/src/Plugin/views/field/MediaLibrarySelectForm.php \Drupal\media_library\Plugin\views\field\MediaLibrarySelectForm::updateWidget()

Submit handler for the media library select form.

Parameters

array $form: An associative array containing the structure of the form.

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

\Symfony\Component\HttpFoundation\Request $request: The current request.

Return value

\Drupal\Core\Ajax\AjaxResponse A command to send the selection to the current field widget.

File

core/modules/media_library/src/Plugin/views/field/MediaLibrarySelectForm.php, line 154

Class

MediaLibrarySelectForm
Defines a field that outputs a checkbox and form for selecting media.

Namespace

Drupal\media_library\Plugin\views\field

Code

public static function updateWidget(array &$form, FormStateInterface $form_state, Request $request) {
    $field_id = $form_state->getTriggeringElement()['#field_id'];
    $selected_ids = $form_state->getValue($field_id);
    $selected_ids = $selected_ids ? array_filter(explode(',', $selected_ids)) : [];
    // Allow the opener service to handle the selection.
    $state = MediaLibraryState::fromRequest($request);
    $current_selection = $form_state->getValue('media_library_select_form_selection');
    $available_slots = $state->getAvailableSlots();
    $selected_count = count(explode(',', $current_selection));
    if ($available_slots > 0 && $selected_count > $available_slots) {
        $response = new AjaxResponse();
        $error = \Drupal::translation()->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($error, '#media-library-messages', [
            'type' => 'error',
        ]));
        return $response;
    }
    return \Drupal::service('media_library.opener_resolver')->get($state)
        ->getSelectionResponse($state, $selected_ids)
        ->addCommand(new CloseDialogCommand());
}

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