Fragmented Thought

Adding Flexibility to Drupal Views Exposed Location Postal Codes

By

Published

Lance Gliser

Heads up! This content is more than six months old. Take some time to verify everything still works as expected.

A client of mine has recently requested that users of their site be able to search their Canadian postal codes more freely. A quick look over the zip codes for Canada shows some interesting variations used by public. The proper postal code could be 'A1W 3A1', but we'll get searches for the variations like these:

  • a1w 3a1
  • A1W-3A1
  • A1W3A1

The first will return results in an exposed distance / proximity filter, but the others are buggered. I fixed this using a form_alter that added a tiny bit of logic to format the postal codes to what the database was expecting. I'll put the code below, but I've also copied my concern over the Location issues queue in the hope this fix won't be required for long, here's the link: http://drupal.org/node/1355148

/** * Implementation of hook_form_FORM_ID_alter */ function custom_form_views_exposed_form_alter(&$form, &$form_state){ switch($form['#id']){ case 'views-exposed-form-local-retailers-page-1': module_load_include('inc', 'custom', 'pages'); custom_form_views_exposed_form_alter_local_retailers_page($form, $form_state); break; } } function custom_form_views_exposed_form_alter_local_retailers_page(&$form, &$form_state){ $form['#validate'][] = custom_form_views_exposed_form_alter_local_retailers_page_validate'; } function custom_form_views_exposed_form_alter_local_retailers_page_validate(&$form, &$form_state){ form_set_value( array( '#parents' => array('distance', 'postal_code') ) ,custom_format_postal_code( $form_state['values']['distance']['country'], $form_state['values']['distance']['postal_code'] ) ,$form_state ); }