Change Exposed Views Filter to Dropdown [Drupal]

How to change exposed filters in Drupal Views. Override exposed filters — change regular text field to dropdown. Useful in changing date filter from manual input to something like “1, 3 or 6 months ago”.

Add a function overriding HOOK_preprocess_views_exposed_form. This function will:

  • check that we’re overriding the appropriate form by checking the form id ($vars['form']['#id']) – lines 12 to 20
  • change the properties of the requested “filter” field to a dropdown and its options – lines 24 to 32
  • “flag” the form to be re-rendered by unsetting the #printed property – line 35
  • Trigger re-rendering with core drupal_render on the “filter” field, updating the fields associated “widget” – line 36
/**
 * Alter specific exposed forms to change the textfield into a select item
 * @param $vars
 * @param $hook
 * @see http://drupal.org/node/320992
 * @seealso http://drupalsn.com/learn-drupal/drupal-questions/question-7534
 */
function MYTHEME_preprocess_views_exposed_form(&$vars, $hook) {
	//http://snipplr.com/view/17307/hookformalter-for-views-exposed-filter-form/
	
	//filter behavior for specified forms, by id
	$allowed_forms = array(
		'views-exposed-form-blog-page-1'
		,'views-exposed-form-newsletters-page-1'
		,'views-exposed-form-press-releases-page-1'
		,'views-exposed-form-reports-page-1'
	);
	
	// filter
	if ( in_array($vars['form']['#id'], $allowed_forms) ) {
		// which form field to override
		$filter = 'created';
		
		$vars['form'][$filter]['#type'] = 'select'; //change type
		$vars['form'][$filter]['#size'] = '1'; //update size to be a dropdown?
		$vars['form'][$filter]['#options'] = array(
			'' => t('Show All')
			,'-1 Month' => t('Last Month')
			,'-3 Months' => t('Last 3 Months')
			,'-6 Months' => t('Last 6 Months')
			,'-1 Year' => t('Last Year')
		);
		
		//tricks the Views into rerendering the filter
		unset($vars['form'][$filter]['#printed']);
		$vars['widgets']['filter-'.$filter]->widget = drupal_render($vars['form'][$filter]);
	}
}//--	fn	MYTHEME_preprocess_views_exposed_form

Sources:

  1. DrupalSN – [sic] how do replacement in view filter expose label for other text. – asks how to change the label, but the re-rendering trick is applicable
  2. How to use hook_form_alter for views exposed filter form – again, changing the label, but has some nice logic for generic overriding

3 thoughts on “Change Exposed Views Filter to Dropdown [Drupal]

  1. I did exactly what you have here and it does replace the filter, but the form no longer submits the value through the query string. Did you have any issues with this happening?

    • This was an old post and most likely specific to Drupal 6, if that’s applicable to you — I don’t recall any issues but it’s been a while since I did anything with this. Sorry I couldn’t be more helpful.

Leave a Reply

Your email address will not be published. Required fields are marked *