Views - Return Empty Result Set on Exposed Filters
I have a view with exposed filters that I want the user to be able to search. Normally when you visit a page with exposed filters, views will list all possible results. What I want is for the list to be empty until the user actually enters something into the box. The following will accomplish that.
Add the argument "Global: Null" to your view.
Configure the new argument as follows:
Action to take if argument is not present:
- Provide default argument
Provide default argument options
- Fixed entry
I didn't actually enter anything in the "Fixed Entry" box. It's only needed to get to the next step, validation.
Validator Options
- PHP Code
if (count($view->exposed_input)) {
return TRUE;
}Action to take if argument does not validate: Display Empty Text
When you visit your view with any argument (or no argument) the validator will run, find exposed_input empty and display your view's empty text. Once you hit submit on the filter it will run as usual.
Say you also want to display a different message if the user simply clicks the search button without entering anything in the exposed field. Put the following in a module and your done.
function YOUR-MODULE-NAME_views_pre_build(&$view) {
$empty_text = "<h4>Please enter a keyword to search for.</h4>";
if ($view->name == 'YOUR-VIEW-NAME' && $view->current_display == 'page_1') {
$filtered = FALSE;
foreach ($view->get_exposed_input() as $name => $value) {
if(!empty($value)) {
$filtered = TRUE;
}
else {
$view->display['page_1']->handler->set_option('empty',$empty_text);
}
}
if(!$filtered) {
$view->executed = TRUE;
}
}
}
Thanks
Thanks for sharing this useful, but not so obvious tip.
My PHP validation code looks for the existence of a keyword argument:
if (isset($_GET['keys'])) {return TRUE;
}
If it's not present, suppress the default results.
Thank you.
I've spent the last week trying to figure this out!