5

I have an exposed filter block on the sidebar on my page. I want to hide the exposed filter block if the result of the view is empty. What is the best was to do it ? Right now i am having some Jquery code in a no result behaviour textfield wich hides some block elements. But i dont like this solution. I prefer if the code is clean and the html code is completely removed.

8

@pierre's answer is a good one, however $view->total_rows is not always populated.

So you could do something like this instead, which will work no matter what:

function MODULE_views_pre_render(&$view) {
  if ($view->name == 'VIEW_NAME' && $view->current_display == 'DISPLAY_NAME') {
    if (empty($view->result) && empty($view->getExposedInput())) {
      $view->exposed_widgets = NULL;
    }
  }
}
  • This solution worked for my use case. – Blake Frederick Oct 17 '17 at 22:07
1

In a custom module, implements hook_form_FORM_ID_alter() for the views_exposed_form form. Start by checking if the form is the one from your view and display, then set its #access property FALSE if the views has no results.

function MODULE_form_views_exposed_form_alter (&$form, &$form_state) {
  $view = &$form_state['view'];
  if ($view->name == VIEW_NAME && $view->current_display == DISPLAY_NAME) {
    if (empty($view->total_rows)) {
      $form['#access'] = FALSE;
    }
  }
}
1

The above suggestions for [function MODULE_form_views_exposed_form_alter(&$form, &$form_state)] are helpful if you want to hide the exposed filters whether or not the results will showing.

So according to yours requirement you can hide filters when no result will found using below code-:

function hook_views_pre_render(&$view){
  if($view->name == VIEW_NAME){
    if(empty($view->result) && isset($view->exposed_widgets)){
        $view->exposed_widgets = FALSE;
      }
   }
}
-2
  1. Go to the advanced tab of you view
  2. Add contextual filters
  3. Select Global: Null
  4. When the filter value is NOT available: Select 'Hide view'
  • Its not working. The View is gone, but the exposed filter block is still there! – oll Nov 5 '13 at 12:21
  • Here is a detailed guide: agentic.ca/blog/… – Druvision Nov 6 '13 at 8:15
  • The answer is incomplete and misses several steps from the referenced article. – Pierre Buyle Mar 15 '14 at 19:51

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.