I have some external data that I have introduced to Drupal for a users address (not in an address field). I am setting it so that when a user loads the checkout page in commerce their info is populated as the default field values.

How do I change the State (administrative area) to match the country that is set? Right now, if I have it set to Australia for instance, the State field is still set to United States relevant states.

Code Example:

    $form['customer_profile_billing']['commerce_customer_address']['und'][0]['#address']['first_name'] = $firstname;
    $form['customer_profile_billing']['commerce_customer_address']['und'][0]['#address']['last_name'] = $lastname;  
    $form['customer_profile_billing']['commerce_customer_address']['und'][0]['#address']['thoroughfare'] = $street;
    $form['customer_profile_billing']['commerce_customer_address']['und'][0]['#address']['locality'] = $city;
    $form['customer_profile_billing']['commerce_customer_address']['und'][0]['#address']['administrative_area'] = $state;
    $form['customer_profile_billing']['commerce_customer_address']['und'][0]['#address']['postal_code'] = $zipcode;
    $form['customer_profile_billing']['commerce_customer_address']['und'][0]['#address']['country'] = $country;
    $form['customer_profile_billing']['commerce_firstdata_billing_phone']['und'][0]['value']['#default_value'] = $phone;

Here is an example, You need to use ajax. I think you will just need to alter the form structure a bit from what I have but the basic logic is there.

$country_list = array(0=>'USA',1=>'Canada');
$value_country = isset($form_state['values']['country']) ? $form_state['values']['country'] : key($country_list);

$form['country'] = array( 
    '#type' => 'select',
    '#title' => t('Select Country'),
    '#options' =>  $country_list,  
    '#ajax' => array(
        'event' => 'change',
        'callback' => 'mymodule_ajax_callback',
        'wrapper' => 'name_replace',

$form['state'] = array( 
    '#type' => 'select',
    '#title' => t('Select State'),
    '#prefix' => '<div id="name_replace"; style="margin-top:50px;">',
    '#suffix' => '</div>',
    '#options' =>  mymodule_find_states($value_country), //pass country, run query, return correct states
    '#default_value' => isset($form_state['values']['country']) ? $form_state['values']['country'] : '',

Add this function make sure this function is NOT inside form_alter function

function mymodule_ajax_callback($form, $form_state) {
    return $form['state'];
|improve this answer|||||
  • I'm not sure if that will work. I am setting the country value from the start of the page load. I don't think there will be a change event. – Aaron Ortega Mar 12 '14 at 22:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.