Skip to main content
view exposed filters

Drupal Views exposed filter as Links

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 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 Link. To display exposed filters as radio button or checkbox, we can utilize Better Exposed Filters module.

Comments

Using hook_form_FORM_ID_alter() instead of hook_form_alter() is usually preferred if only altering a single form, since that will only be called for the form in question, not for all forms on the whole site.
The function name would then be module_name_form_views_exposed_form_alter().

mike (not verified)

Fri, 11/14/2014 - 07:09

Just FYI: The Better Exposed Filters module also allows you to render exposed filter options as links (in addition to checkboxes, radio buttons, etc.).