I added an exposed filter (as described here) to let visitors filter the View by country.

But in the exposed filter select list, all enabled countries are listed. Is it possible to only list those countries that are already entered in the country field on nodes?

Comments

IanNorton’s picture

I've got exactly the same requirement, I've started working on the solution, but it's a little rough around the edges and I'm not 100% sure there isn't a better way to do it using the views UI, I would expect that this is a requirement that comes up fairly often with views and lists.

Initially I worked to check if there are any nodes available for each country as the filter populated and didn't write the country name if so this seemed pretty query intensive, so I changed tact and came up with this below in template.php:

function YOURTHEME_form_alter(&$form, &$form_state, $form_id) {
if ($form_id == 'views_exposed_form' && $form['#id'] == 'views-exposed-form-customers-2013-block-1' && isset($form['name_list'])){
    $output = '';
    $output = cache_get('views-exposed-form-customers-2013-block-1-name_list', 'cache');
    if (empty($output)) {
      $result = db_query("SELECT DISTINCT iso2, name from {field_data_field_country} f LEFT JOIN {countries_country} c ON f.field_country_iso2 = c.iso2 WHERE f.bundle = 'customer' ORDER BY name ASC");
      $defaultoptions = array('All'=>'- Any -');
      $output = $defaultoptions + $result->fetchAllKeyed();
      $form['name_list']['#options'] = $output;
      cache_set('views-exposed-form-customers-2013-block-1-name_list', $output, 'cache');
    }else{
	  $form['name_list']['#options'] = $output->data;
    }
  }
}

You'll note I've added caching to the code here as well and specified a content type to refine the query by, you may not want these but both were worthy additions in our case.

vinmassaro’s picture

@IanNorton: I'm going to test your solution out - was this your final code? Thanks.

Alan D.’s picture

Status: Active » Fixed

Something along these lines is the best bet. You may want a timeout on the cache, otherwise this data could get stale.

Closing to clean up the queue a bit.

IanNorton’s picture

@vinmassaro yes that was it, it's been working nicely since then.

Status: Fixed » Closed (fixed)

Automatically closed -- issue fixed for 2 weeks with no activity.

RAWDESK’s picture

Issue summary: View changes

#1 worked for me.
I even replaced the db_query with a more generic
$view = views_get_view();
$view->execute_display();