hello everybody

I would like to create a form to retrieve a postal code.
In this form there is 2 fields :
- CityName
- PostalCode

I made an autocomplete field for Cityname, and it works fine. My aim is to auto fill the PostalCode when the user pick up a cityname in the autocomplete cityname list. Any idea how to implement that ?

Thank you for any advice.

Nicolas

Comments

nicopepe’s picture

thank you for any comment.

nicolas

nicopepe’s picture

I presume nobody had an idea for this question. Soafter searching a lot i found a solution that may help anybody.


 //- 1 - My form 
...
   $form['city'] = array(
        '#type' => 'textfield',
        '#title' => t('City'),
        '#default_value' =>  '',
        '#size' => 25,
        '#maxlength' => 100,
        '#autocomplete_path' => 'city/autocomplete', // autocomplete Drupal
        '#attributes' => array('onchange' => 'javascript:document.getElementById(\'edit-postalcode\').value=
document.getElementById(\'edit-city\').value.substr(35,5);'),
        '#description' => t('city name')
    );
    $form['postalcode'] = array(
         '#type' => 'textfield',
         '#title' => t('Postal Code'),
         '#default_value' => '',
         '#size' => 5,
         '#maxlength' => 5,
         '#description' => t('Postal cod input')
    );
....
//- 2 - autocomplete function
function mag_city_autocomp($ville) {
  $matches = array();
  $sql = "SELECT city,city_upper,zip FROM {af_villes} n WHERE 
(n.city_upper LIKE UPPER('%s%%')) ORDER BY n.city ASC ";
  $sql = db_rewrite_sql($sql);
  $result = db_query_range($sql, $ville, 0, 15);
  while ($foundville = db_fetch_object($result)) {
  	$matches[str_pad($foundville->city_upper,35).strval($foundville->zip)] = strval($foundville->zip)." ".check_plain($foundville->city);
  }
  print drupal_to_js($matches);
  exit();
}

//- 3 - MENU
    $items[] = array('path' => 'city/autocomplete',
                     'title' => t('city autocomplete'),
                     'callback' => 'mag_city_autocomp',
                     'access' => user_access('city autocomplete'),
                     'type' => MENU_CALLBACK);  

I hope it may help. Just a little javascript in the #attribute made the trick !!!