SearchAPI Autocomplete - Pass in contextual filter to alter query

by propel   Last Updated January 12, 2018 18:07 PM

I'm trying to modify the Autocomplete module query with hook_search_api_alter_query. I would like to pass in the contextual filter of the page I embed the search in into the module so I can add it to the query. In a hook_search_api_alter_query function I wrote, I just used arg(1), which works for the actual search, however when the autocomplete module runs, var_dump(arg(1)) returns Response Type: string(33) followed by the autocomplete results and their html tags.

Is it possible to pass in the contextual filter into the autocomplete module so that I can use it , since the contextual filter has been changed to /search_api_autocomplete/search_api_views_[view name]/-?

My current query alter hook:

    function hook_search_api_query_alter(SearchApiQueryInterface $query) {
      var_dump(arg(1));
        $prod_code = arg(1);
        $tid = taxonomy_get_term_by_name($prod_code);
        if (!empty($tid)) {
            $base_filter = $query->createFilter('AND');
            $or_filter = $query->createFilter('OR');
            while (!empty($tid)) {
                $or_filter->condition('field_prod_code', array_shift($tid)->tid);
            }
            $base_filter->filter($or_filter);
            $query->filter($base_filter);
        }
    }

My problem is that arg(1) within the autocomplete module isn't the taxonomy term, therefore the function doesn't go through the if statement. I need a way to get the contextual filter for the autocomplete function so that it can alter my query like it does when searching.

Tags : 7


Answers 1


I ran into the same issue. You could save your data in a session in hook_init or hook_boot.

/**
 * Implements hook_init().
 */
function hook_init() {
  $arg = arg();
  if (isset($arg[2]) && $arg[0] == 'taxonomy' && $arg[1] == 'term' && is_numeric($arg[2]) ) {
    $_SESSION['last_term'] = $arg[2];
  }
}
mfrosch
mfrosch
January 12, 2018 17:08 PM

Related Questions