I'm trying to build a custom search form, and I want to limit the scope of the search with a dropdown select menu, ie. choose "jewelry" in the dropdown menu and the autocomplete form will only return matches of that category.
Here's what I have so far:
function mymodule_search_menu() {
$items['mymodule_search-autocomplete-test'] = array(
'title' => 'Test autocomplete',
'page callback' => 'drupal_get_form',
'page arguments' => array('category'),
'access arguments' => array('view published content'),
'type' => MENU_NORMAL_ITEM,
);
$items['mymodule_search-autocomplete-engine'] = array(
'page callback' => 'mymodule_search_autocomplete',
'access arguments' => array('view published content'),
'type' => MENU_CALLBACK,
);
return $items;
}
function mymodule_search_form($form, &$form_state) {
$form = array();
$form['category'] = array(
'#type' => 'select',
'#title' => 'First Dropdown',
'#options' => array('All','Product'),
'#ajax' => array(
'callback' => 'mymodule_search_ajax_callback',
'wrapper' => ???,
'method' => ???,
),
);
$form['search_autocomplete'] = array(
'#title' => t('Search'),
'#type' => 'textfield',
'#maxlength' => 60,
'#autocomplete_path' => 'mymodule_search-autocomplete-engine',
'#prefix' => '<div id="searchform">',
'#suffix' => '</div>',
);
$form['submit'] = array(
'#type' => 'submit',
'#value' => 'Søg alt',
);
return $form;
}
function mymodule_search_autocomplete($text) {
$results = array();
//query products
$query_products = db_select('commerce_product', 'p');
$query_products
->condition('p.title', '%' . db_like($text) . '%', 'LIKE')
->fields('p', array('title'))
->orderBy('title', 'ASC');
$res = $query_products->execute();
while ($res1 = $res->fetchAssoc()) {
$matches[1][$res1['title']] .= check_plain($res1['title']);
}
array_unshift($matches[1], "PRODUCTS");
//query content
$query_content = db_select('node', 'n');
$query_content
->condition('n.title', '%' . db_like($text) . '%', 'LIKE')
->fields('n', array('title'))
->orderBy('title', 'ASC');
$res = $query_content->execute();
while ($res2 = $res->fetchAssoc()) {
$matches[2][$res2['title']] = check_plain($res2['title']);
}
array_unshift($matches[2], "CONTENT");
$matches = mymodule_search_flatten($matches);
$newmatches = array();
foreach ($matches as $match){
$newmatches[$match] = $match;
}
drupal_json_output($newmatches);
}
function mymodule_search_ajax_callback($form, $form_state) {
???
}
As you might see, I have 2 different querys in my autocomplete function, and (I think) I would like to limit the result to only the selecteded querys with help of an ajax call from the dropdown category.
Oh, and don't mind all the "unshifting" and looping that goes on in the autocomplete function - I have to have category headers in my result, and this was the only way I could think of to do that.
If there's a better way to do this, or if you know how to accomplish this, please let me know.
Thanks!!