I have a menu "Display Style Switcher" which has two links: Map, and List. You click Map, you get the Map display of search results, and if you click List you get the list display of search results. The List and Map displays are two different displays of the same view.

Both variations of the display results leverage a views exposed form and facets which all share the same query string identifiers.

My requirement is all links in the "Display Style Switcher" menu should inherit the current query string parameters of the request (at least, I think this is the way to go). So, while in the List display and you have activated a few filters (which sets query string arguments), if you switch to the Map display your current result set should be maintained (the same query string arguments are preserved and passed to the List display of the view).

What would be the right approach to implementing this?

1 Answer 1


I ended up solving this by building the tree and menu render array and injecting it into the view template in a preprocess function (this is fired for both displays on the view).

The key point was collecting the query string arguments from the current request and using that to set the query string option for each menu link element in the tree.

 * Implements hook_preprocess_HOOK().
function mc_location_explorer_preprocess_views_view__program_location_search_api(&$variables) {
  // Generate the Map/List display menu and inject into the listing and map view
  // templates.
  $menu_name = 'program-search-displays';
  /** @var \Drupal\Core\Menu\MenuLinkTreeInterface $menu_tree */
  $menu_tree = \Drupal::service('menu.link_tree');
  $params = $menu_tree->getCurrentRouteMenuTreeParameters($menu_name);
  $manipulators = [
    ['callable' => 'menu.default_tree_manipulators:checkAccess'],
    ['callable' => 'menu.default_tree_manipulators:generateIndexAndSort'],
  $tree = $menu_tree->load($menu_name, $params);

  // Attach current requests query string parameters to each display link, in
  // order to preserve the current filters and facets in a user's search.
  $query_params = \Drupal::request()->query->all();
  foreach ($tree as $item) {
    $item->options['query'] = $query_params;
  $tree = $menu_tree->transform($tree, $manipulators);
  $build = $menu_tree->build($tree);
  // Because we attached query string parameters for the current page to each
  // link in the menu, we need to vary the menu's cacheability by query string.
  $build['#cache']['contexts'][] = 'url.query_args';
  $variables['search_display_switcher'] = $build;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.