How to unset or hide a view header / footer when an exposed filter is being applied?

by Adrian Cid Almaguer   Last Updated January 10, 2018 15:07 PM

I have a header in a view that should be visible only if there are no values in the exposed filters. So, once the user enters any value in any filter and sends the form, this header should not be visible. And the same for a footer in other views.

How to unset or hide a view header / footer when an exposed filter is being applied?



Answers 2


I found this solution that is really very simple:

use Drupal\views\ViewExecutable;
/**
 * Implements hook_views_pre_view().
 */
function MODULE_views_pre_view(ViewExecutable $view, $display_id, array &$args) {
  if ($view->id() == 'nouvelles' && $display_id === 'block_1' && !empty($view->getExposedInput())) {
    $view->removeHandler($display_id, 'header', 'view');
    //or 
   // $view->removeHandler($display_id, 'header', $view->getHandlers('header')['view']['id']);
  }
}

With the getExposedInput() function you can figures out what the exposed input for this view is, so wee need to check if the returned value is not empty.

The function removeHandler() is the key here, but wee need to know:

public ViewExecutable::removeHandler($display_id, $type, $id)

$display_id -> is in the function params
$type -> can be header or footer
$id -> view (see the getHandlers() output)

You can found additional info with the getHandlers() function:

dpm($view->getHandlers('header'));
Array (
    [view] => Array
        (
            [id] => view
            [table] => views
            [field] => view
            [relationship] => none
            [group_type] => group
            [admin_label] => 
            [empty] => 1
            [view_to_insert] => en_vedette:block_1
            [inherit_arguments] => 
            [plugin_id] => view
        )

)
Adrian Cid Almaguer
Adrian Cid Almaguer
December 05, 2016 22:05 PM

For a Better Approach, you can use:

hook_preprocess_views_view(&$variables)

And Apply condition on the basis of $view->exposed_data

And Implement it in the Views Twig file: For Example: In sub_theme.theme

if($view->exposed_data['type'] = 'content_type'){
$variables['this_val'] = 'content_type_name';
}

In Views.html.twig

{% if this_val == 'content_type_name' %}
{{ footer }}
{% endif %}
Lovejit S.
Lovejit S.
January 10, 2018 14:31 PM

Related Questions


Exposed filters go to request arguments

Updated June 04, 2015 02:03 AM

How to alter combined filter value programatically?

Updated March 27, 2015 14:18 PM



How to set up this view of commerce orders...?

Updated January 11, 2017 10:03 AM