You are here

public function MediaLibraryFieldWidgetOpener::getSelectionResponse in Drupal 9

Same name and namespace in other branches
  1. 8 core/modules/media_library/src/MediaLibraryFieldWidgetOpener.php \Drupal\media_library\MediaLibraryFieldWidgetOpener::getSelectionResponse()

Generates a response after selecting media items in the media library.

Parameters

\Drupal\media_library\MediaLibraryState $state: The state the media library was in at the time of selection, allowing the response to be customized based on that state.

int[] $selected_ids: The IDs of the selected media items.

Return value

\Drupal\Core\Ajax\AjaxResponse The response to update the page after selecting media.

Overrides MediaLibraryOpenerInterface::getSelectionResponse

File

core/modules/media_library/src/MediaLibraryFieldWidgetOpener.php, line 116

Class

MediaLibraryFieldWidgetOpener
The media library opener for field widgets.

Namespace

Drupal\media_library

Code

public function getSelectionResponse(MediaLibraryState $state, array $selected_ids) {
  $response = new AjaxResponse();
  $parameters = $state
    ->getOpenerParameters();
  if (empty($parameters['field_widget_id'])) {
    throw new \InvalidArgumentException('field_widget_id parameter is missing.');
  }

  // Create a comma-separated list of media IDs, insert them in the hidden
  // field of the widget, and trigger the field update via the hidden submit
  // button.
  $widget_id = $parameters['field_widget_id'];
  $ids = implode(',', $selected_ids);
  $response
    ->addCommand(new InvokeCommand("[data-media-library-widget-value=\"{$widget_id}\"]", 'val', [
    $ids,
  ]))
    ->addCommand(new InvokeCommand("[data-media-library-widget-update=\"{$widget_id}\"]", 'trigger', [
    'mousedown',
  ]));
  return $response;
}