Skip to content

Instantly share code, notes, and snippets.

@vilepickle vilepickle/yourtheme.theme
Last active Jan 11, 2016

Embed
What would you like to do?
Manipulate search tab URLs in Drupal 8
/**
* Implements hook_pre_render_HOOK() for menu-local-tasks templates.
*
* Changes search tab URLs if you have more than one search page to be able
* to automatically search the other page when you navigate to it.
* This snippet assumes two search plugins:
* search.plugins:node_search (core)
* search.plugins:content_part (custom)
*
* This snippet assumes two search routes:
* search.view_node_search (core)
* search.view_content_part (custom)
*/
function yourtheme_preprocess_menu_local_tasks(&$variables) {
$keys = \Drupal::request()->query->get('keys');
if($keys && is_array($variables['primary']['search.plugins:node_search']) && is_array($variables['primary']['search.plugins:content_part'])) {
// Get the current URL minus query params
$url = @( $_SERVER["HTTPS"] != 'on' ) ? 'http://'.$_SERVER["SERVER_NAME"] : 'https://'.$_SERVER["SERVER_NAME"];
$url .= ( $_SERVER["SERVER_PORT"] !== 80 ) ? ":".$_SERVER["SERVER_PORT"] : "";
// Make a new URL with query params and assign it to the node search tab link
$search_node_url = $variables['primary']['search.plugins:node_search']['#link']['url'] =
\Drupal\Core\Url::fromRoute('search.view_node_search', [], ['query' => ['keys' => $keys]]);
// Tab links get cached unless we clear this
$variables['primary']['search.plugins:node_search']['#access']->setCacheMaxAge(1);
// Make a new URL with query params and assign it to the content part search tab link
$search_content_part_url = $variables['primary']['search.plugins:content_part']['#link']['url'] =
\Drupal\Core\Url::fromRoute('search.view_content_part', [], ['query' => ['keys' => $keys]]);
// Tab links get cached unless we clear this
$variables['primary']['search.plugins:content_part']['#access']->setCacheMaxAge(1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.