Limiting select options for exposed filter

Limiting select options for exposed filter

FFW Marketing
Thought byFFW Marketing
Website Administrator
May 17, 2013

While I was working on a project here at FFW, I had a requirement to limit the options for an exposed filter in order to get only options that will give some results. Unfortunately Views don’t provide this kind of functionality.

Let's start with an example. I have a Content Type called "People" which has a Term Reference select list. Generally speaking we have to alter the “views_exposed_form”.

Follow the next 3 steps:

1. Create a custom module and implement hook_form_alter(). I strongly recommend not to use a form-specific alteration like hook_form_FORM_ID_alter() instead of global hook_form_alter()because it is difficult to control and manage your code.

function [my-module-name]_form_alter) { dsm($form); //be sure to enable devel module. }

2. Now you should get the content from the $form variable

3. Next, we have to select all the matching results based on our conditions in order to edit the options from $form['term']['#options']. Personally, I prefer to query directly with db_select, but feel free to use EntityFieldQuery if you prefer.

function [my-module-name]_form_alter(&$form, &$form_state, $form_id) { if ($form['#id'] == 'views-exposed-form-people-list-page') { $available_terms = _get_available_terms(); if (isset($available_terms)) { // Unset the existing list and add new one with available terms. unset($form['term']['#options']); $form['term']['#options']['All'] = '- Any Term -'; foreach ($available_terms as $available_term) { $form['term']['#options'][$available_term->tid] = $available_term->name; } } else { // Unset all options except '- Any -' unset($form['term']['#options']); $form['term']['#options']['All'] = '- Any Term -'; } } }

function _get_available_terms() { $query = db_select('taxonomy_term_data', 'terms'); $query->join('field_data_field_reference', 'term_ref', 'term_ref.field_reference_tid = terms.tid'); $term_result = $query ->fields('terms', array('tid', 'name')) ->execute() ->fetchAll(); return $term_result; }

That's it.

Topics:
drupal

Read next:

Blog
Teaser image of DrupalCon Seattle

Proud Platinum Sponsor of DrupalCon 2019

Blog
Teaser image of March trainings

Spring forward into Drupal in March

Blog
Teaser of Eastern bank blog

New Case Study: Eastern Bank and Join Us For Good

Blog
Teaser of 7 Things Before Starting a Drupal Project blog

7 Things to Think About Before Starting a New Drupal Project