First. please don't confuse this issue with #1152760: Using country list as select list in views exposed filter..
Basically, I wonder if it's possible to have a select list as an exposed filter for State address field. This could be a bit tricky, as not all Countries have a specific set of states defined in plugins/format/address.inc. Also, this should be dependent on Country filter to expose relevant states.
Please advise if this is possible or any direction about coding this feature.

Support from Acquia helps fund testing for Drupal Acquia logo

Comments

webankit’s picture

Alternative: I think you can use Location Taxomonize Module to apply a Taxonomy...

Remon’s picture

@babbar.ankit, thank!, but this is not even an option for me :P

webankit’s picture

FYI: It is compatible with addressfield also

stewart.adam’s picture

I would appreciate this as well, it would be very great to have a drop-down selection of states/provinces, even better if it has an option to limit the possibly options to the ones available in the query results.

Yaazkal’s picture

I vote for this, is a needed feature :)

Yaazkal’s picture

Category: feature » support

I have found a way. I can update a patch but is not a good one because is just one question left. Let me explain how to make it work.

In views/addressfield.views.inc, put this on line 24 (just before return $data;):

// Add a handler for administrative area.
  foreach ($field['storage']['details']['sql'] as $type => $tables) {
    foreach ($tables as $table_name => $columns) {
      if (!isset($columns['administrative_area'])) {
        continue;
      }
      
      $column_real_name = $columns['administrative_area'];
      if (!isset($data[$table_name][$column_real_name]['filter'])) {
        continue;
      }

      $data[$table_name][$column_real_name]['filter']['handler'] = 'addressfield_views_handler_filter_administrative_area';
    }
  }

Then create a file views/addressfield_views_handler_filter_administrative_area.inc with this code (if dosen't work just add this code at the end of views/addressfield_views_handler_filter_country.inc without the first line <?php):

<?php
class addressfield_views_handler_filter_administrative_area extends views_handler_filter_in_operator {
  function get_value_options() {
    $this->value_title = t('Administrative Area');
    $field = field_info_field($this->definition['field_name']);
    $this->value_options = array(
          // Put the list of your states/province/departments or whatever here.
          // These are just examples
  	  'AMA' => t('Amazonas'),
  	  'ANT' => t('Antioquia'),
  	  'ARA' => t('Arauca'),
  	);
  }
}

I have put the same array for my country administrative area as in #1707192: Add Columbian administrative areas (departments)

This could be an answer. But is not a pretty one answer because it assumes that you will use only one country and all that administrative areas are fixed, so this is a "manual" answer, is near and it will work in case you will use only one country and need that feature fast (as I do).

It will be nicer if there is a function that given X country (the selected country in the form of exposed filters) it retrieves all its administrative area names. Could be to retrieve all the administrative areas that are defined in plugins/format/address.inc but this implies more work and I don't have the time to do it right now. So, this is a fast not-very-well solution but works.

Any idea about how to finish it?

Regards!

Yaazkal’s picture

Category: support » feature
aitala’s picture

Category: support » feature

I'm running into the same issue for US States... I may try the 'fix' in #6 at some point.

Eric

adamwhite’s picture

I just tried out the solution in #6 and it does work. Granted I'm just hard-coding the US states in for the time being as a test:

 class addressfield_views_handler_filter_administrative_area extends views_handler_filter_in_operator {
  function get_value_options() {
    $this->value_title = t('Administrative Area');
    $field = field_info_field($this->definition['field_name']);
    $this->value_options = array(
      'AL' => t('Alabama'),
      'AK' => t('Alaska'),
      'AZ' => t('Arizona'),
      'AR' => t('Arkansas'),
      'CA' => t('California'),
      'CO' => t('Colorado'),
      'CT' => t('Connecticut'),
      'DE' => t('Delaware'),
      'FL' => t('Florida'),
      'GA' => t('Georgia'),
      'HI' => t('Hawaii'),
      'ID' => t('Idaho'),
      'IL' => t('Illinois'),
      'IN' => t('Indiana'),
      'IA' => t('Iowa'),
      'KS' => t('Kansas'),
      'KY' => t('Kentucky'),
      'LA' => t('Louisiana'),
      'ME' => t('Maine'),
      'MD' => t('Maryland'),
      'MA' => t('Massachusetts'),
      'MI' => t('Michigan'),
      'MN' => t('Minnesota'),
      'MS' => t('Mississippi'),
      'MO' => t('Missouri'),
      'MT' => t('Montana'),
      'NE' => t('Nebraska'),
      'NV' => t('Nevada'),
      'NH' => t('New Hampshire'),
      'NJ' => t('New Jersey'),
      'NM' => t('New Mexico'),
      'NY' => t('New York'),
      'NC' => t('North Carolina'),
      'ND' => t('North Dakota'),
      'OH' => t('Ohio'),
      'OK' => t('Oklahoma'),
      'OR' => t('Oregon'),
      'PA' => t('Pennsylvania'),
      'RI' => t('Rhode Island'),
      'SC' => t('South Carolina'),
      'SD' => t('South Dakota'),
      'TN' => t('Tennessee'),
      'TX' => t('Texas'),
      'UT' => t('Utah'),
      'VT' => t('Vermont'),
      'VA' => t('Virginia'),
      'WA' => t('Washington'),
      'WV' => t('West Virginia'),
      'WI' => t('Wisconsin'),
      'WY' => t('Wyoming'),
      'DC' => t('District of Columbia'),
  	);
  }
}

One thing I noticed is that unless I put the code in addressfield_views_handler_filter_country.inc it would give me an error of:

Notice: Undefined index: field_address_administrative_area in views_handler_filter->accept_exposed_input() (line 1260 of /xxxxx/sites/all/modules/views/handlers/views_handler_filter.inc).

EDIT: Actually I believe I've resolved this. I wasn't adding the file include to the addressfield.info

files[] = views/addressfield_views_handler_filter_administrative_area.inc

Of course, #6 is totally correct that this should ideally be dynamic. I'll see what I can do.

adamwhite’s picture

Looking into this, the countries dropdown is being populated by the country code / country name pairs stored in the iso.inc file in core. There doesn't appear to be anything similar for administrative_area (state / province).

As for grabbing some dynamic list of administrative areas from current locations, it appears that that the only thing the database appears to store is the two-letter abbreviation, so we'd still need to have some additional list of abbreviation / name pairs kicking around.

mo3.mo3’s picture

Version: 7.x-1.x-dev » 7.x-1.0-beta3
Priority: Normal » Major

i have been looking for this.

Ideal would be to allow admin to pick a Country as an exposed filter and in the settings, it allows an option to display States/Province. It then displays the Country as a drop down in the front end and based on the country, States/Province drop down show up similar to how it does when filling in the address (during the creation of the content). If only one country is used, then if admin adds Country as exposed filter and chooses to display States/Province then in the front end it only shows a drop down for States/Province.

This way, we can allow visitors to filter content by Country and then States/Province and further more, allow Zipcode and City filter as well.

Also, can anyone please direct me to a good tutorial on how to use Location Taxomonize module?

thanks!

rajmataj’s picture

Nicely done, Yaazkal and adamwhite. I have also successfully implemented this workaround with 7.x-1.0-beta3 using Canadian provinces and territories. Although it is hard-coded, at least it works for now until the developer can integrate these features into the next release. Here's the code I used for Canada (note, I only needed the abbreviated prov/terr's for the value, but you can of course substitute the full names yourself).

<?php
class addressfield_views_handler_filter_administrative_area extends views_handler_filter_in_operator {
  function get_value_options() {
    $this->value_title = t('Administrative Area');
    $field = field_info_field($this->definition['field_name']);
    $this->value_options = array(
        'AB' => t('AB'),
        'BC' => t('BC'),
        'MB' => t('MB'),
        'NB' => t('NB'),
        'NL' => t('NL'),
        'NS' => t('NS'),
        'NT' => t('NT'),
        'NU' => t('NU'),
        'ON' => t('ON'),
        'PE' => t('PE'),
        'QC' => t('QC'),
        'SK' => t('SK'),
        'YT' => t('YT'),
      );
  }
}

lathan’s picture

related issue as this needs ajax callback in the options of this filter #1183418: Ajax attached to exposed filters in form_alter doesn't trigger callback.

rerooting’s picture

Looks like some great progress is being made!

Can we expect patches for this, and eventually a commit, or is this going to remain more of a per use case, custom implementation kind of thing?

Heres how I would love the views handlers to work:

The choices in administrative area can be limited by the availability of the 'country' filters. So for example, if I allow country filters of only US and Canada, then I can have the administrative areas list be of 'state/province' and the user can select from there states or canadian provinces. If the user already has applied a country filter, or has chosen a different value in the country filter, then the available administrative areas would be limited/expanded to reflect this choice. Ideally.

This way, a (or multiple) seperate array would not be necessary, as we already have the built-in ISO codes and strings, correct? This could at least work *only* when a filter country is selected, and thus call up the specific administrative area options via ajax by borrowing some of the functionality from the addressfield form?

Thoughts?

rszrama’s picture

Title: Using State/AdministrativeArea as a select list in Views exposed filter » Add a Views handler to filter by administrative area using a select list instead of a textfield
Version: 7.x-1.0-beta3 » 7.x-1.x-dev
Priority: Major » Normal

This will be dependent on #1829900: [meta] Address Field 2.x needs pluggable administrative areas and an actual API, as we don't have an easy API for getting at the lists of administrative area data (without building the form for a country and extracting the #options list). We definitely don't want to implement a handler that simply duplicates those state / province lists. : )

One thing I don't get about this feature request, though... are you guys fine with the country being an hardcoded option? Otherwise how should the handler know which administrative areas to populate the select list with?

rerooting’s picture

Ryan,

good question!

I was thinking it could behave in one of two ways:

1. A combined Country/Administrative Area exposed filter handler, with options

2. Separate but mutually aware country/admin area handlers

Either way, the administrative area field could be in a disabled or hidden state until you choose country, which would then populate the administrative area option list via AJAX. Thus behaving somewhat like the addressfield form itself. This could even extend further down the line if the issue you mentioned gets into some fancy solutions for sub admin areas, etc.

I can also recall once, on a D6 site, using Location, I had two filters of note - one that was not exposed of 'country' where I chose US and Canada, and the other, which was exposed, of administrative areas which I labeled 'State/Province'. It populated the list with both US states and Canadian provinces (doesn't work with the latest version of location though, just checked, haha!). This could get very unwieldy once you ratchet the filter up to multiple (or all!) countries with lots of administrative areas. However, its a flexibility option that might prove useful to some.

Also, I'd like the choices to be available as select or autocomplete fields, and to allow multiple of course! And a pony!

pyxio’s picture

Am I correct in understanding this functionality already exists on the node edit/add form? If I choose US from countries the City, State and Zip fields dynamically appear with States pre-populated. I just want to ensure the same functionality is not possible to accomplish with views exposed filters yet. Or perhaps it does and I am configuring it wrong. Just needed a confirmation on this. Thanks. Kevin

rerooting’s picture

Hey Kevin!

Good question, I myself wondered the same thing.

It is not currently available, despite it being available in the field widget. As Ryan seems to indicate, it was very difficult for the addressfield folks to get this working because currently the API for fetching all these various data items is not super flexible (or really a true API?). Once this part of addressfield is refactorered per the issue he indicated, a views handler filter as such should be far easier to implement.

Meanwhile, I've got a strong hunch that I can get this working via Views Autocomplete Filters per recent experimentations with this module. I will be glad to share my results in a blog post on this issue until the upstream issue is resolved with addressfield.

rerooting’s picture

Quick reportback on VAF : does not seem possible OOTB, but a patch to addressfield or VAF might seal the deal on this provisional fix.

Meanwhile, if folks are interested in moving this along, I'd suggest following Ryan's advice and jumping in on #1829900: [meta] Address Field 2.x needs pluggable administrative areas and an actual API and related issues with testing, patches, ideas, etc.

Additionally, I'd suggest giving further input re: Ryan's questions regarding how we envision these filters to be implemented.

rszrama’s picture

Right, the big question is how do you determine the country to use in the select list. The simplest format would be a giant list of checkboxes in the filter options - hardly an appealing UI, but the simplest way to give admins access to control which administrative areas are used to populate the list. On the address field widget form, we know the country because it's part of the form input, so it's no problem there to restrict the administrative area options to the currently selected country.

pyxio’s picture

Hey there,

Ahhh what a pity. I think this a REALLY important module. I took a quick look at the Views Autocomplete Filters module and not to sure that is going to integrate seamlessly with this module without a lot of elbow grease. But if you figure it out please let me know. I am sure the good folks here on top of it as well. Anyway, see you over on the Radix side. I wonder why they don't have an HTML5 theme yet!!! Cheers, Kevin

Taz’s picture

Status: Active » Needs review
FileSize
3.15 KB

See patch, an elegant way that exposes this select option for a number of the columns available on the address field

pyxio’s picture

Hi taz,

I am very surprised there has been no feedback on this if in fact it does work! I will give it a try today and report back. Thanks. kevin

pyxio’s picture

Taz,

I was unable to apply the patch

b < 1304288-select-exposed-views-filter.patch
patching file addressfield.module
can't find file to patch at input line 40
Perhaps you should have used the -p or --strip option?
The text leading up to this was:
--------------------------
|diff --git a/views/addressfield.views.inc b/views/addressfield.views.inc
|index 77a5b45..bb0fe97 100644
|--- a/views/addressfield.views.inc
|+++ b/views/addressfield.views.inc
--------------------------

stewart.adam’s picture

You will most likely need to use the -p1 option, for more information please see Applying Patches.

hass’s picture

Status: Needs review » Needs work
+++ b/views/addressfield.views.incundefined
@@ -9,16 +9,37 @@ function addressfield_field_views_data($field) {
+      if (isset($columns['administrative_area'])) {
+        $column_real_name = $columns['administrative_area'];
+        if (isset($data[$table_name][$column_real_name]['filter'])) {
+          $data[$table_name][$column_real_name]['filter']['handler'] = 'addressfield_views_handler_filter_column';
+        }
+      }
+      if (isset($columns['sub_administrative_area'])) {
+        $column_real_name = $columns['sub_administrative_area'];
+        if (isset($data[$table_name][$column_real_name]['filter'])) {
+          $data[$table_name][$column_real_name]['filter']['handler'] = 'addressfield_views_handler_filter_column';
+        }
+      }
+      if (isset($columns['locality'])) {
+        $column_real_name = $columns['locality'];
+        if (isset($data[$table_name][$column_real_name]['filter'])) {
+          $data[$table_name][$column_real_name]['filter']['handler'] = 'addressfield_views_handler_filter_column';
+        }
+      }
+      if (isset($columns['dependent_locality'])) {
+        $column_real_name = $columns['dependent_locality'];
+        if (isset($data[$table_name][$column_real_name]['filter'])) {
+          $data[$table_name][$column_real_name]['filter']['handler'] = 'addressfield_views_handler_filter_column';
+        }

This could be written a lot shorter. Use in_array() and you are able to reduce this to one if() condition or more easier to read, use a switch statement.

sheldonkreger’s picture

After applying the patch in #22, I am getting a missing/broken handler error when I try to add the exposed filter administrative_area.

jhedstrom’s picture

The patch from #22 appears to be missing the new handler addressfield_views_handler_filter_column that it references.

paul53181’s picture

Issue summary: View changes

I have the same issue as well.

heshanlk’s picture

A new patch attached with the US states.

heshanlk’s picture

Status: Needs work » Needs review
oranges13’s picture

Status: Needs review » Reviewed & tested by the community

Patch #30 works for me! Ack, I forgot to add there's a call to dsm(); in the patch code which will probably break anyone without devel enabled.

Yogesh Kushwaha’s picture

Is it available for all countries? I have installed dev version but it is not coming. Also I Tried #30 on simpletest but got error.

oranges13’s picture

@yogesh.kushwaha89 You will need to manually apply the patch in comment #30

It has a call to dsm(); which requires that devel be installed and enabled which is probably why it is not working on simpletest, either. But yeah, patches are not automatically included in dev versions unless they're marked as committed.

oranges13’s picture

Status: Reviewed & tested by the community » Needs review
FileSize
3.52 KB

Here's an updated patch that removes the call to dsm(); so it should be production ready.

Yogesh Kushwaha’s picture

Thanks #oranges13,
#35 works for me thanks again.

lunk rat’s picture

#35 works perfectly. Hunk #1 failed for me when I ran patch -p1 < 1304288-add-default-state-values-35.patch

So I just patched the .info file manually.

The functionality works great.

epringi’s picture

Just thought I'd drop a patch that applies to the latest dev in the interim, since I've come across the need for a select list as well. Also with Canadian provinces.

Any progress on making this patch more dynamic?

NWOM’s picture

#35 and #38 didn't work for me sadly. Not sure if it has to do with my custom address format module which adds the Administrative Area field for Germany, or if it has to do with the view being a Search API indexed view.

Either way, as a workaround, I added a Grouped Exposed Filter instead which let me add each value for the dropdown manually. I figured this might help those that can't get the patch working.

brooke_heaton’s picture

#38 is bringing up Canadian Provinces only for me. No US States. US States have been removed from patch.

jenlampton’s picture

Status: Needs review » Needs work

Looks like there are three confirmations that the recent patches here still need work. #35 seems to only add US states, and #38 adds only canadian provinces. Both are hard coded.

I've created a views handler for Backdrop CMS that provides a select list for both Country and Administrative Area. The options in the Administrative Area field are determined by the selection made in the Country field, which is why they are paired together.

It would likely take minimal effort to port this back over to Drupal if anyone is interested in taking it on.

Pull Request: https://github.com/backdrop-contrib/addressfield/pull/11
Patch link: https://github.com/backdrop-contrib/addressfield/pull/11.patch

rszrama’s picture

Thanks for sharing, Jen! Just saw that you'd made an Address Field port when I was checking out 1.3. : )

dave.erwin’s picture

Here is the patch from #35 fixed so you don't have to manually copy the line in the info file.

DrCord’s picture

I was able to port over the Backdrop CMS addressfield country and administrative area code from jenlampton. It took a bit off work and diffing as some of the integral parts of this upgrade had been added to Backdrop addressfield in previous commits. I tracked down those additional changes via diff and added them to make this work as well as making the "Any/All/all" searches work right for both country and administrative district/state/province.

Currently this only shows the administrative districts (also known as states or provinces) that you have addressfield entries for on the field you are using in your exposed filter. This is different than the above patches with the lists hardcoded where you get a full list for the US or Canada, which seems less smart and kinda more frustrating while using the filter but more expected by the general user...I could easily see this being added as a toggle setting on the views exposed filter, to either only show the administrative areas you have data for or to show them all.

This patch is against the latest dev version.

DrCord’s picture

Status: Needs work » Needs review
DrCord’s picture

oof, apparently i added a bunch of whitespace errors, I will clean those up and resubmit this patch, not sure why I got those, but will make it happy :D

DrCord’s picture

Ok, I think I got the whitespace errors fixed in this now, it applies for me fine now to the latest dev.

EDIT: it may only apply cleanly to the latest dev on windows...I'm checking for more whitespace errors now...

EDIT: Nope, seems to work fine on linux, I think this patch may be good to go, if I find anything more weird that needs updated/changed in it I will re-roll it but it works for me and applies cleanly.

EDIT: this patch applies cleanly via `git apply [patchname]` but does not with the "patch" utility. If anyone knows the difference and what to do to fix this, please let me know.

NWOM’s picture

Maybe it has something to do with all of the white spaces. I was having issues as well with Drush Issue Queue Commands and for some reason I couldn't create a patch after removing the white spaces. If you highlight the entire file, you'll see that there are a lot of white spaces still which seems to be the same problem that I was having. I sadly didn't find a fix.

DrCord’s picture

Here is a patch without whitespace issues, this one works for me applying it with git or patch.

joelstein’s picture

Status: Needs review » Needs work

It seems the patch in #49 is missing the Views handler files...?

  • views/addressfield_views_handler_argument_countryname.inc
  • views/addressfield_views_handler_filter_country_admin.inc
DrCord’s picture

That doesn't seem to be the case for me, but if you want to reroll the patch go ahead.

joelstein’s picture

Status: Needs work » Needs review

My bad, for some reason my find/replace was being wonky.

Anas_maw’s picture

#49 works for me
Thanks

oranges13’s picture

#49 doesn't apply for me. I tried using a drush .make file and I also tried patch directly.

Hunk #1 FAILED at 2.
1 out of 1 hunk FAILED -- saving rejects to file addressfield.info.rej
can't find file to patch at input line 506
Perhaps you should have used the -p or --strip option?
The text leading up to this was:
--------------------------
|diff --git a/views/addressfield.views.inc b/views/addressfield.views.inc
|index f059da3..4e31adc 100644
|--- a/views/addressfield.views.inc
|+++ b/views/addressfield.views.inc
--------------------------
can't find file to patch at input line 679
Perhaps you should have used the -p or --strip option?
The text leading up to this was:
--------------------------
|diff --git a/views/addressfield_views_handler_filter_country.inc b/views/addressfield_views_handler_filter_country.inc
|index d1b11c1..d98035a 100644
|--- a/views/addressfield_views_handler_filter_country.inc
|+++ b/views/addressfield_views_handler_filter_country.inc
--------------------------
oranges13’s picture

Status: Needs review » Needs work
oranges13’s picture

#43 is working for us in production if we want to go to RTBC with that patch

biarr’s picture

Patch #49 workes for me. Good solution, thanks!

NWOM’s picture

@oranges13, did you apply #49 to the newest dev or stable?

oranges13’s picture

@NWOM in my drush make file I have the following

addressfield:
    version: 1.x-dev
    patch:
      # https://www.drupal.org/node/1304288#comment-10943487
      #- 'https://www.drupal.org/files/issues/1304288-add-default-state-values-43.patch'
      - https://www.drupal.org/files/issues/addressfield-views-handler-filter-country-admin-district-select-1304288-49-7.patch

The patch from #43 applies, the patch from #49 does not apply.

For giggles and grins, I also tried using the newest stable in the drush.make file instead, and it also failed.

NWOM’s picture

Oh ok, just was making sure you were applying it to a dev release (since I hadn't tried stable). Weird, via "git apply -v" it applied cleanly for me.

gillesmpem’s picture

Noticed in addressfield-7.x-1.2, addressfield_views_handler_filter_country is properly called, however addressfield_views_handler_field_country and addressfield_views_handler_field_administrative_area are not being called at all.
What I mean is they being totally ignored by Drupal.
Anyone ever tried it out?
Any fix for this?

oranges13’s picture

Circling back to this. I got the patch from #49 to apply, by completely blowing away the module directory and re-downloading it from git.

Installing the module with `drush make` and drush patching did not work with the patch from #49. I had to manually download 1.x-dev from version control and apply the patch with `git apply` and even then there were whitespace errors listed.

So, the patch from #49 DOES NOT DO what the previous patches did. This does not fix the "Administrative Area" filter into a select list, it only seems to add its own "Country And Administrative Area" filter, which won't work for my use case. In the case of our site, we have a default country, which this newer filter isn't honoring. You can't set a default (to the USA or Canada, for instance) and expose only the state select box, which is what I need it to do.

NWOM’s picture

@oranges13, as you can see from the comments, every person that said #49 worked has most likely used Address Field with Administrative Areas outside of the USA (based on the country in their profile), whereas #30, #35, and #43 literally handles only the USA (since the states are directly added to the patch).

Also, there are numerous Administrative Area addressfield submodules for specific countries which should be taken into account as well.

I may be missing something, but maybe having a closer look at both patches (#43 & #49) with respect to ALL countries, might be a better approach.

Edit:

@joelstein did #49 end up working for you?

dapseen’s picture

I have been following this issue since 2014, hopefully the following patch i'm about to try works

oranges13’s picture

Yes, my issue as it stands now is that for the USA specifically, Addressfield includes places like "Puerto Rico" and the "U.S. Virgin Islands" in the select list for state addresses, but the hard-coded patches don't include that.

#49 doesn't solve my use case because we want to have a default country but still have state as a select box (so it accomplishes half of what we need.)

If we could somehow add default choices to the views filter, that would be great.

aitala’s picture

I think this is the patch time forgot...

Anyone else have a solution?

E

oranges13’s picture

Unfortunately it depends a lot on what you need. Many of the solutions are country-of-coder specific. For my use case, I rolled a custom patch that fits our use case (USA, including some of the outlying islands but not all of them). Unfortunately I know that won't work for 100% of the drupal audience so I did not provide it.

aitala’s picture

@oranges I would not mind seeing that patch as that would be more maintainable than the current situation.

Or would it be possible to roll a custom module to handle this? Then have a way to share those?

Eric

oranges13’s picture

@aitala Here is the patch.

In my case, we needed all 50 US states + Puerto Rico. Those are hard coded, however so it's not very transferrable to other users.

aitala’s picture

I'm using basically the same patch but w/o PR.

Eric