Creating a "collapsible" Views Exposed Filter

When building sites for our customers we usually create some administrative views (like for content or user administration) to make it easier for editors to work with the site. For a little more user experience we modify these views (especially the exposed form providing the filters). One of these modifications is to create a "collapsible" filter dropdown.

The Mission

Think of a content administration view with filters for content type, status, author and so on. Normally the filter for the content type allows multiple selections and would look similar to the one in the image.

But we want the filter to act as a single dropdown that could be expanded to a multi-select list if the user wants to filter for several types.

The Solution

To achieve this we need a small custom module and alter the exposed form:

  1. <?php
  2. /**
  3.  * Implements hook_form_FORM_ID_alter().
  4.  *
  5.  * Alter views exposed forms for collapsible filters.
  6.  */
  7. function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state) {
  8.   if (empty($form_state['view']) || !in_array($form_state['view']->name, array('NAME_OF_VIEW', 'NAME_OF_VIEWS_DISPLAY'))) {
  9.     // We alter the exposed form of a single views display, so return if this is
  10.     // not the expected view.
  11.     return;
  12.   }
  13.  
  14.   if (isset($form['type'])) {
  15.     // Add option to select all items (equals to resetting the filter).
  16.     $options = array(
  17.       'All' => variable_get('views_exposed_filter_any_label', 'new_any') == 'old_any' ? t('<Any>') : t('- Any -'),
  18.     );
  19.     $options += $form['type']['#options'];
  20.     // Change size of field based on number of options (max: 5 items).
  21.     $form['type']['#size'] = min(array(count($options), 5));
  22.  
  23.     if (count($options) <= 2) {
  24.       // Hide filter if there is only one option available (additional
  25.       // to "All").
  26.       $form['type']['#access'] = FALSE;
  27.     }
  28.     $form['type']['#options'] = $options;
  29.   }
  30.  
  31.  
  32.   // Alter multi-value dropdowns.
  33.   $form_multiple_selects = array();
  34.   foreach (element_children($form) as $element_name) {
  35.     if (isset($form[$element_name]['#type']) && $form[$element_name]['#type'] == 'select' && !empty($form[$element_name]['#multiple'])) {
  36.       $form_multiple_selects[$element_name] = array(
  37.         'size' => isset($form[$element_name]['#size']) ? $form[$element_name]['#size'] : 5,
  38.       );
  39.     }
  40.   }
  41.   if (count($form_multiple_selects)) {
  42.     $form['#attached'] += array(
  43.       'js' => array(),
  44.       'css' => array(),
  45.     );
  46.     // Attach custom javascript to the form.
  47.     $form['#attached']['js'][] = drupal_get_path('module', 'MYMODULE') . '/js/MYMODULE.admin.js';
  48.     $form['#attached']['js'][] = array(
  49.       'data' => array(
  50.         'collapsibleFilter' => array(
  51.           'multiple_selects' => $form_multiple_selects,
  52.         ),
  53.       ),
  54.       'type' => 'setting',
  55.     );
  56.   }
  57. }
  58. ?>
  59.  

Unfortunately we have to do some more magic to avoid errors after selecting the new option "All". Because we manually added the option in the form-alter, Views does not know about it and would throw an error after selecting it. The simplest way to avoid it, is to remove the filter value before displaying the results:

  1. <?php
  2. /**
  3.  * Implements hook_views_pre_view().
  4.  */
  5. function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {
  6.   if (!in_array($view->name, array('NAME_OF_VIEW', 'NAME_OF_VIEWS_DISPLAY'))) {
  7.     return;
  8.   }
  9.   foreach (array('type') as $filter) {
  10.     if (!empty($_GET[$filter]) && (is_array($_GET[$filter])) && reset($_GET[$filter]) == 'All') {
  11.       // Remove the filter value because it is manually added and thus
  12.       // unknown to Views.
  13.       unset($_GET[$filter]);
  14.     }
  15.   }
  16. }
  17. ?>
  18.  

Finally we add our JavaScript to append the "plus sign" to the dropdown and add the "collapse" functionality:

  1. (function($) {
  2.  
  3.   /**
  4.    * Change multi-value dropdown to single-value dropdown and back (visually).
  5.    */
  6.   Drupal.behaviors.collapsibleFilterRewriteMultipleSelect = {
  7.     attach: function(context, settings) {
  8.       $.each(Drupal.settings.collapsibleFilter.multiple_selects, function(name, settings) {
  9.         $('select#edit-' + name)
  10.               .once('collapsible-filter-multiple-rewrite')
  11.               .each(function() {
  12.  
  13.           var selectionCount = $('option:selected', $(this)).length;
  14.           if (selectionCount <= 1) {
  15.             // Set size of select to 1 if there is not more than 1 selected.
  16.             $(this).attr('size', 1);
  17.             // Remove attribute "multiple".
  18.             $(this).removeAttr('multiple');
  19.             // Set default option.
  20.             if (selectionCount === 0 || $(this).val() === 'All') {
  21.               $(this).val('All');
  22.             }
  23.  
  24.             // Add link to expand the dropdown.
  25.             $expand = $('<a>')
  26.                     .addClass('select-expander')
  27.                     .attr('href', '#')
  28.                     .attr('title', Drupal.t('Expand selection'))
  29.                     .html('[+]')
  30.                     .click(function() {
  31.                       // Get corresponding select element.
  32.                       $select = $(this)
  33.                               .parent('.form-type-select')
  34.                               .find('.collapsible-filter-multiple-rewrite-processed');
  35.                       // Expand element.
  36.                       $select.attr('size', settings.size)
  37.                               .attr('multiple', 'multiple');
  38.                       $(this).remove();
  39.                     })
  40.                     .appendTo($(this).parent());
  41.           }
  42.         });
  43.       });
  44.     }
  45.   };
  46.  
  47. })(jQuery);
  48.  

Result

After you have all this together, users will be able to choose whether to select a single type from a dropdown or multiple values from a list. If a user selected multiple values the filter automatically displays as select list. 

 

Stefan Borchert
  • CEO

Stefan maintains several Drupal contributed modules, has been working on Drupal core since the early days, and is author of Drupal 8 Configuration Management (Packt Publishing).