views:

77

answers:

6

I know that one way is to have a table in database with all the states and then you would read it in your form. Is there any easier way in your opinion guys ?

I feel bad asking for something like this since it is so elementary however I would suppose something as simple like this would already be implemented in Drupal.

+1  A: 

No need to hit the database. Build yourself a function that returns an array of the states.

$form['state'] = array(
  '#type' => 'select',
  '#options' => mymodule_states_list(),
  '#title' => t('State'),
);

function mymodule_states_list() {
  return array(
    'AL' => 'Alabama',
    'AK' => 'Alaska',
    ...
    'WY' => 'Wyoming',
  );
}
ceejayoz
A: 

If you're building the form using Drupal's FormAPI you could just include the array of states in your module code since the names and abbreviations shouldn't be changing any time soon.

If you're trying to keep your code clean, you could save an array of states as a Drupal variable using variable_set() and then retrieve it using variable_get(). You really shouldn't need to bother with the database for that kind of thing.

wynz
where would I "set" the variables? Is there a specific place where such code is placed in Drupal?
A: 

That is one way to do it, sure. You can store a list of states as a variable, and call it.

$options = variable_get('mymodule_us_states', 0);

So long as it's an array. You could also have an internal function that returns the states.

Kevin
The variables table is loaded into memory on every page load, so this will up your site's memory usage a bit.
cam8001
A: 

Or store it in a flat file and read it in. Eg

Flat file =

$us_states_options = array(
 'AL' => 'Alabama',
 'AK' => 'Alaska',
//...etc
)

Function:

include_once(drupal_get_path('module', 'module_name') .'/us_states.inc');

All pretty ugly, but you at least can edit that file independently, and may work well if you have a larger list. Theres a million ways you could have the list included - using exec, fgetcsv/file, etc....

But I think ceejayoz solution is the nicest. I'd probably spin out those sorts of utility functions into a seperate include to keep it clean myself.

cam8001
A: 

The Country codes API module also provides a Regions codes API module which include US states. With this module, you can get an array suitable for a Form API select element by calling regions_api_iso2_get_options_array('US').

mongolito404
A: 

Just remembered this question as I was experimenting with the Geonames module. Among tons of other features, Geonames includes the function "geonames_us_states()" which returns an array of U.S. states keyed by the states' two letter code.

wynz

related questions