Filtering Drupal Views with first letter

Drupal Views now comes with a contextual filter that filters content by the first letter, which is a great feature. But it's a contextual filter, not a regular filter. If you start experimenting with the glossary view, which using this feature, you'll notice it places the letter in the url and changes pages. You can't use it for ajax filtering and you can't use it easily with other filters, or as an exposed filter. That's exactly what I needed, an exposed filter, so I built a module to handle this problem. It's a very simple module that you can recreate for your Views projects. First, create your view and add a filter on your text field. Set the operator option to "Starts with," and expose it. Then you'll see the textfield input where you can enter a single letter. There we have our first letter search. Now we need to format it into links. Then you'll need to get Better Exposed Filters (BEF). Make the .info file with a dependency on BEF and Views.

name = ABC Filter
description = Change search textfield starts with to letter click for first letter search.
core = 7.x
version = 7.x-1.0

dependencies[] = views
dependencies[] = better_exposed_filters

Now we need a very simple .module file to change what the user sees. There is one function, altering the form - mymodule_form_views_exposed_form_alter().

/**
* Implements hook_form_alter()
*/
function abcfilter_form_views_exposed_form_alter(&$form, &$form_state, $form_id) {
  	// set up array of letters 	$letters = array('' =----> '');
	foreach (range('a', 'z') as $letter) {
		$letters[$letter] = strtoupper($letter);
	}

	// add the new options and adjust other settings to change the exposed filter
	$form['field_name'] += array(
		'#type' => 'select',
		'#theme' => 'select_as_links',
		'#size' => '',
		'#default_value' => '',
		'#options' => $letters,
	);
}

There you have it. A quick and easy way to create your own first letter exposed filter for Drupal Views.

Category: