Using the default Drupal search block to get the results in Views
Drupal 7 will no longer be supported after January 5, 2025. Learn more and find resources for Drupal 7 sites
I am using Search API in Views with many exposed filters. My client wants a search block in the site's header that shows the results in Views. I only need one filter on the header, not all the others, so I can't use Exposed form in block. Also, when seeing the results, I need all the exposed filters to be shown in top of the results, not in the header. I didn't find a solution in internet, so I write my solution code here. If you know a better solution, please, add it in the comments.
I have created a simple module to solve the problem.
Steps:
- Add the search block wherever you want
- Create a view with Search API. Remember the URL
- Create a module (YOUR-MODULE-NAME.info YOUR-MODULE-NAME.module
- Inside the YOUR-MODULE-NAME.info write:
name = YOUR-MODULE-NAME description = "Something that you will remember" core = 7.x
- Copy inside YOUR-MODULE-NAME.module copy the following code
Module:
/**
* Implementation of hook_form_alter()
*/
function YOUR-MODULE-NAME_form_alter(&$form, &$form_state, $form_id) {
if($form_id == 'search_block_form') {
$form['#submit'][0] = 'YOUR-MODULE-NAME_form_submit';
}
}
/**
* Process a block search form submission.
*/
function YOUR-MODULE-NAME_form_submit($form, &$form_state) {
$keys = $form_state['values']['search_block_form'];
// The search form relies on control of the redirect destination for its
// functionality, so we override any static destination set in the request,
// for example by drupal_access_denied() or drupal_not_found()
// (see http://drupal.org/node/292565).
if (isset($_GET['destination'])) {
unset($_GET['destination']);
}
// Check to see if the form was submitted empty.
// If it is empty, display an error message.
// (This method is used instead of setting #required to TRUE for this field
// because that results in a confusing error message. It would say a plain
// "field is required" because the search keywords field has no title.
// The error message would also complain about a missing #title field.)
if ($form_state['values']['search_block_form'] == '') {
form_set_error('keys', t('Please enter some keywords.'));
}
else {
$form_state['redirect'] = array(
'VIEW_RESULTS_URL',
array(
'query' => array(
'search_api_views_fulltext' => $keys,
),
),
);
}
}
Help improve this page
You can:
- Log in, click Edit, and edit this page
- Log in, click Discuss, update the Page status value, and suggest an improvement
- Log in and create a Documentation issue with your suggestion