function MediaLibraryHooks::viewsPostRender

Implements hook_views_post_render().

File

core/modules/media_library/src/Hook/MediaLibraryHooks.php, line 153

Class

MediaLibraryHooks
Hook implementations for media_library.

Namespace

Drupal\media_library\Hook

Code

public function viewsPostRender(ViewExecutable $view, &$output, CachePluginBase $cache) {
    if ($view->id() === 'media_library') {
        $output['#attached']['library'][] = 'media_library/view';
        if (str_starts_with($view->current_display, 'widget')) {
            try {
                $query = MediaLibraryState::fromRequest($view->getRequest())
                    ->all();
            } catch (\InvalidArgumentException $e) {
                // MediaLibraryState::fromRequest() will throw an exception if the view
                // is being previewed, since not all required query parameters will be
                // present. In a preview, however, this can be omitted since we're
                // merely previewing.
                // @todo Use the views API for checking for the preview mode when it
                //   lands. https://www.drupal.org/project/drupal/issues/3060855
                if (empty($view->preview) && empty($view->live_preview)) {
                    throw $e;
                }
            }
            // If the current query contains any parameters we use to contextually
            // filter the view, ensure they persist across AJAX rebuilds.
            // The ajax_path is shared for all AJAX views on the page, but our query
            // parameters are prefixed and should not interfere with any other views.
            // @todo Rework or remove this in https://www.drupal.org/node/2983451
            if (!empty($query)) {
                $ajax_path =& $output['#attached']['drupalSettings']['views']['ajax_path'];
                $parsed_url = UrlHelper::parse($ajax_path);
                $query = array_merge($query, $parsed_url['query']);
                // Reset the pager so that the user starts on the first page.
                unset($query['page']);
                $ajax_path = $parsed_url['path'] . '?' . UrlHelper::buildQuery($query);
            }
        }
    }
}

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