Inline Labels for Views Exposed Filters

  • henok_mikre

    Henok Mikre

Inline labels in views exposed filters

In views exposed filters, changing labels to display inline can seem more work than necessary. When using a Bootstrap template, it can easily be done by adding grid classes to the form element. There are various methods to add the classes, including views hooks and template files. Some filters like "order by" can present a challenge. The quickest may be to use jQuery, however. Here we will describe how we used jQuery to add classes to exposed filters.

First we need to create a js file in our custom module:

vi blen_visualization/js/blen_visualization.js
(function ($) {
  Drupal.behaviors.blenVisualization = {
    attach: function (context, settings) {
      // Add classes for "order by" filter.
      $(".exposed-filters-wrapper .views-widget-sort-order label").addClass(
        "col-sm-3"
      );
      $(".exposed-filters-wrapper .views-widget-sort-order select").addClass(
        "col-sm-9"
      );
    },
  };
})(jQuery);

The above code will find both the label and the input and add the Bootstrap classes that have the appropriate properties to display the items inline.

We now need to call the js file on the page.

vi blen_visualization/blen_visualization.module
/**
 * Implements hook_preprocess_page.
 */
function blen_visualization_preprocess_page(&$vars) {
  $vars['is_default_theme'] = path_to_theme() . drupal_get_path('theme', variable_get('theme_default', NULL));

  // Only process pages for the default theme.
  if (!$vars['is_default_theme']) {
    return;
  }

  // Customize Visualization landing page.
  if (request_uri() == '/visualization') {
    drupal_add_js(
      drupal_get_path('module', 'blen_visualization') . '/js/blen_visualization.js',
      array('every_page' => TRUE)
    );
  }
}

The above snippet will ensure the js file is called on the specific page and for the default theme.