0

How do I get the value of searched item value, if I searched for "cat" in a search box then it also displays on a search page?

2
  • How do you want to use it?
    – Eugene
    May 23 '15 at 11:03
  • Just need to display it like in a variable
    – nomeer
    May 23 '15 at 11:05
0

You can catch your entity in the preprocess and put data into drupal_static. After that you can display it where you want.

0

This way sometimes works, in a hook_alter function:

if ($form_id == 'search_form'){
  // gives you the value
  $save_value = $form['basic']['keys']["#default_value"];
}

But this way seems to work even better:

\Drupal::request()->query->get('keys')

There should technically also be a way of making a custom module, add a custom submit handler to the search form, and getting the value in there, but I couldn't get it working that way.

1
  • Oh, I forgot to mention the second part. To display on your search results page, override the search-results twig template and use the variable from the .theme file.
    – user72565
    Feb 8 '17 at 14:57
0

Though I am seriously late to the party, you can also grab the query thusly if you use the Search API module. After you created a View associated to your search index, you can use:

/**
 * Implements hook_preprocess_views_view()
 * @param $variables
 */
function YOUR_THEME_NAME_preprocess_views_view(&$variables) {
  if ($variables['view']->id() == 'search') {
        $variables['search_keywords'] = \Drupal::request()->query->get('search_api_fulltext');
  }
}

In this case, my view is named "search" and the query key I am looking for (after the ?) is "search_api_fulltext" (id of my input search field).

$variables['search_keywords'] will now contain the keywords after the "=", for instance from /search?search_api_fulltext=searched+term

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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