7

When using Drupal 7, how do I print the current search terms into a search form in a block?

In Drupal 6, I used something like this in my template.php:

$vars['search_keys'] = search_get_keys();

Then, in search-theme-form.tpl.php I had:

<input type="text" value="<?php print $search_keys; ?> name="search_theme_form" id="edit-search-theme-form-1">

But search_get_keys doesn't exist in Drupal 7, so I can't use this method.

Using arg(2) is the only method I've come up with, but that seems a little hacky, because it will break if the URL ever changes.

6

If you're using Apache Solr (http://drupal.org/project/apachesolr) you can use

$query->getParam("q")

in your search-result.tpl.php template.

Otherwise, you can use the slightly modified version of the function above:

function get_current_search_terms() {
// only do this once per request
static $return;
    if (!isset($return)) {
        // extract keys from path
        $path = explode('/', $_GET['q'], 3);
        // only if the path is search (if you have a different search url, please modify)
        if(count($path) == 3 && $path[0]=="search") {
            $return = $path[2];
        } else {
            $keys = empty($_REQUEST['keys']) ? '' : $_REQUEST['keys'];
            $return = $keys;
        }
    }
    return $return;
}

edit: no need for check_plain here

3

Here's what I've come up with:

function mytemplate_preprocess_search_block_form(&$vars) {

  $path_args = arg();

  // Insert the current search term (if applicable).
  $value = (count($path_args) == 3 && (strpos($path_args[0], 'search') !== false)) ? filter_xss($path_args[2]) : '';

  $vars['search_form'] = str_replace('value=""', 'value="' . $value . '"', $vars['search_form']);

}

Is there a better way to do this?

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.