Pages

Friday, February 28, 2014

A Drupal Dropdown List of Countries, States, Cities

We had a question from a member this week. He was collecting information from users and wanted to collect addresses:
"I need to have a user select a state in a list. My next requirement is to populate a new list with all the counties for the selected state."
It's easy to imagine many more people wanting to do something similar, so in this tutorial we'll explain how it's done.
This tutorial could be used to show Continents and then Countries, Countries and the States, States and then Cities or any similar combination you need. We're going to use the Conditional Fields module.

Installation

Install the Conditional Fields module: https://drupal.org/project/conditional_fields
Yes, it is marked as a dev version for Drupal 7, but it worked for us without any problems.

Add the fields

Add your data fields as you would normally.
In this example, our first field would be a list of the US states. We're going to add these as a List (text) field.
media_1379091240827.png
We enter a list of all 50 states into the field:
media_1379091343156.png
Now we repeat the process for the counties in each state. Start alphabetically with Alabama Counties:
media_1379091420401.png
And enter all a list of all the counties.
media_1379091458618.png
You will need to repeat this 49 more times, creating a field for each state.

Managing Dependencies

The Conditional Fields module adds a new tab called "Manage Dependencies" to the top of the fields area. Click that tab.
media_1379091576338.png
The Manage Dependencies tab is organized into Dependents and Dependees.
In this example, the Dependents are the counties and the Dependees are the States. Our first setup will be this:
  • Dependent: Alabama Counties
  • Dependees: US States
Click Add dependency.
media_1379091619850.png
The key setting for the field is "Insert Value from Widget". Make sure you choose the State that will trigger the list of counties. In this example, we choose Alabama.
media_1379091651885.png
You will need to repeat this 49 more times, creating a dependency for each state.

Test the dependencies

Go to create a new item for your content type and see whether the dependencies are working.
In our example, only the states field will show:
media_1379091719975.png
However, if we select the Alabama option, then the Alabama Counties field will appear.
media_1379091796680.png

No comments:

Post a Comment

Thanks for your comment.