Display Views result only when exposed filters are set

Appnovation put a small Views tutorial online today, which hides the results of a View with exposed filters on initial display, when no filter value is set. However, the shown approach has a small performance backdraw: it hooks into the view to discard the result after querying the database. A code snippet on drupal.org avoids this by adding an impossible condition to the query, however it requires the use of a dummy argument and – worse – PHP to be executed in Views' argument handler.

Here's how to do it avoiding above pitfalls (put in custom.module):
 * Implementation of hook_views_query_alter().
function custom_views_query_alter(&$view, &$query) {
  if ($view->name == 'My_View' && $view->current_display == 'page') {
    // Don't display results until at least one exposed filter has a value set.
    $filter_set = FALSE;
    foreach ($view->filter as $filter) {
      // Check if we've found a filter identifier that is set.
      if ($filter->options['exposed'] && array_key_exists($filter->options['expose']['identifier'], $_GET)) {
        $filter_set = TRUE;
    // If the filter isn't set, add a WHERE clause to the query that
    // cannot be TRUE. This ensures the view returns no results.
    if (!$filter_set) {
      $query->add_where(0, 'FALSE');
      // To display a different message (or no message at all) you
      // also might want to adjust the Views' empty text. 
      //$view->display_handler->options['empty'] = '';

1 comment:

Mark Tawin said...

Hi Stefan
I'm writing to you because I casually found your post;you seem very knowledgeable on exposed filter and I can not find anything on this topic.
Simply: do you think it could be possible to create a hack to put a WHERE condition in the first exposed filter? I'll explain better. With my first exposed filter I choose a gallery from which i will see the content (images nid dependant)to edit.Galleries has a flag open/close with whom I would like to select those that are still to be edited, otherwise, in the long time i will have too long galleries name.
I can not put cascade AND condition in the view because view is set to Node-Type Images. I should then be able to select the still "open". Do you think may be possible to hack this process ?
Thanks a lot and sorry if i disturbed.