3

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?

3

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
        )

)
  • 1
    Interesting, never had to do this, but could come in handy in the future :) – No Sssweat Dec 6 '16 at 2:02
  • @NoSssweat yes is very rare, but maybe for the future is useful for many people. – Adrian Cid Almaguer Dec 6 '16 at 15:27
1

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 %}
  • Thanks for your solution but in your case you need to modify 2 files, I think that is better only write code in a hook. – Adrian Cid Almaguer Jan 10 '18 at 15:25
  • Thanks - Actually I have not found the value of Selected Better Exposed Filter in the hook_view_pre_view(). Albeit Whatever works for you :) – Lovejit S. Jan 10 '18 at 15:58
  • I'm not using better exposed filter. – Adrian Cid Almaguer Jan 10 '18 at 16:24

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.