blog-banner

Drupal Views Exposed Filter as Links

  • Drupal 7
  • Drupal Planet
  • Views

In Drupal views, we have the option of exposing the filters to users. By default, the exposed filters are displayed as Select boxes. Recently in a multilingual project, there was a requirement to display Courses based on Language. And the Languages had to be shown as links. In order to achieve this functionality, the Views exposed filter had to be customized.

To start with the customization, we need to alter "views_exposed_form" using hook_form_alter

function module_name_form_alter(&$form, &$form_state, $form_id) {
  global $language;
  if ($form['#id'] == 'views-exposed-form-course-listing-page') {
    $links = $form['language']['#options'];
    $vars = array();
    foreach ($links as $tid => $term_name) {
      if ($language->language != $tid && $tid != 'All')  {
        $options = array(
          'attributes' => array(
            'class' => array( 'course-filter-tab' . $tid),
            'id' => $tid,
          ),
          'html' => TRUE,
        ),
        $language_list = language_list();
        $language_title = $language_list[$tid]->name;
        $vars['items'][] = l($language_title, "course", $options);
      }
    }
    $vars['type'] = 'ul';
    $vars['attributes']['class'] = array('course-tabbed-filter');
    $prefix = theme('item_list', $vars);
    $form['links'] = array(
      '#markup' => $prefix,
    );
  }  
}

The above code will help us render the select box as a link, but to make the links functional we need some jQuery code.

$('.course-filter-tab').click(function(e) {
  e.preventDefault();
  var id = $(e.target).attr('id');
  var filter = $('#views-exposed-form-course-listing-page select[name="language"]');
  filter.val(id);
  filter.trigger('change');
  $('#views-exposed-form-course-listing-page').submit();
});

Now the Views exposed filter will be shown as a Link. To display exposed filters as radio buttons or checkboxes, we can utilize the Better Exposed Filters module.

Get awesome tech content in your inbox