Upgrade Your Drupal Skills

We trained 1,000+ Drupal Developers over the last decade.

See Advanced Courses NAH, I know Enough

Creating a "collapsible" Views Exposed Filter

Parent Feed: 

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. /**

  2.  * Implements hook_form_FORM_ID_alter().

  3.  *

  4.  * Alter views exposed forms for collapsible filters.

  5.  */

  6. function MYMODULE_form_views_exposed_form_alter(&$form, &$form_state) {

  7.   if (empty($form_state['view']) || !in_array($form_state['view']->name, array('NAME_OF_VIEW', 'NAME_OF_VIEWS_DISPLAY'))) {
  8.     // We alter the exposed form of a single views display, so return if this is

  9.     // not the expected view.

  10.     return;

  11.   }

  12.   if (isset($form['type'])) {
  13.     // Add option to select all items (equals to resetting the filter).

  14.       'All' => variable_get('views_exposed_filter_any_label', 'new_any') == 'old_any' ? t('') : t('- Any -'),
  15.     );

  16.     $options += $form['type']['#options'];

  17.     // Change size of field based on number of options (max: 5 items).

  18.     if (count($options) <= 2) {
  19.       // Hide filter if there is only one option available (additional

  20.       // to "All").

  21.       $form['type']['#access'] = FALSE;

  22.     }

  23.     $form['type']['#options'] = $options;

  24.   }

  25.   // Alter multi-value dropdowns.

  26.   $form_multiple_selects = array();
  27.   foreach (element_children($form) as $element_name) {

  28.     if (isset($form[$element_name]['#type']) && $form[$element_name]['#type'] == 'select' && !empty($form[$element_name]['#multiple'])) {
  29.       $form_multiple_selects[$element_name] = array(
  30.         'size' => isset($form[$element_name]['#size']) ? $form[$element_name]['#size'] : 5,
  31.       );

  32.     }

  33.   }

  34.   if (count($form_multiple_selects)) {
  35.     $form['#attached'] += array(
  36.       'js' => array(),
  37.       'css' => array(),
  38.     );

  39.     // Attach custom javascript to the form.

  40.     $form['#attached']['js'][] = drupal_get_path('module', 'MYMODULE') . '/js/MYMODULE.admin.js';

  41.     $form['#attached']['js'][] = array(
  42.       'data' => array(
  43.         'collapsibleFilter' => array(
  44.           'multiple_selects' => $form_multiple_selects,

  45.         ),

  46.       ),

  47.       'type' => 'setting',

  48.     );

  49.   }

  50. }

  51. ?>

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. /**

  2.  * Implements hook_views_pre_view().

  3.  */

  4. function MYMODULE_views_pre_view(&$view, &$display_id, &$args) {

  5.   if (!in_array($view->name, array('NAME_OF_VIEW', 'NAME_OF_VIEWS_DISPLAY'))) {
  6.     return;

  7.   }

  8.   foreach (array('type') as $filter) {
  9.     if (!empty($_GET[$filter]) && (is_array($_GET[$filter])) && reset($_GET[$filter]) == 'All') {
  10.       // Remove the filter value because it is manually added and thus

  11.       // unknown to Views.

  12.       unset($_GET[$filter]);
  13.     }

  14.   }

  15. }

  16. ?>

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

  1. (function($) {

  2.   /**

  3.    * Change multi-value dropdown to single-value dropdown and back (visually).

  4.    */

  5.   Drupal.behaviors.collapsibleFilterRewriteMultipleSelect = {

  6.     attach: function(context, settings) {

  7.       $.each(Drupal.settings.collapsibleFilter.multiple_selects, function(name, settings) {

  8.         $('select#edit-' + name)

  9.               .once('collapsible-filter-multiple-rewrite')

  10.               .each(function() {

  11.           var selectionCount = $('option:selected', $(this)).length;

  12.           if (selectionCount <= 1) {

  13.             // Set size of select to 1 if there is not more than 1 selected.

  14.             $(this).attr('size', 1);

  15.             // Remove attribute "multiple".

  16.             $(this).removeAttr('multiple');

  17.             // Set default option.

  18.             if (selectionCount === 0 || $(this).val() === 'All') {

  19.               $(this).val('All');

  20.             }

  21.             // Add link to expand the dropdown.

  22.             $expand = $('')
  23.                     .addClass('select-expander')

  24.                     .attr('href', '#')

  25.                     .attr('title', Drupal.t('Expand selection'))

  26.                     .html('[+]')

  27.                     .click(function() {

  28.                       // Get corresponding select element.

  29.                       $select = $(this)

  30.                               .parent('.form-type-select')

  31.                               .find('.collapsible-filter-multiple-rewrite-processed');

  32.                       // Expand element.

  33.                       $select.attr('size', settings.size)

  34.                               .attr('multiple', 'multiple');

  35.                       $(this).remove();

  36.                     })

  37.                     .appendTo($(this).parent());

  38.           }

  39.         });

  40.       });

  41.     }

  42.   };

  43. })(jQuery);

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. 

Original Post: 

About Drupal Sun

Drupal Sun is an Evolving Web project. It allows you to:

  • Do full-text search on all the articles in Drupal Planet (thanks to Apache Solr)
  • Facet based on tags, author, or feed
  • Flip through articles quickly (with j/k or arrow keys) to find what you're interested in
  • View the entire article text inline, or in the context of the site where it was created

See the blog post at Evolving Web

Evolving Web