Skip to main content
1 of 3

Dynamic select list in the form API (dependent dropdown list)?

First I want to select State (like Tamil Nadu, Sikkim, Kerala) after selecting state, depended city list will be display another dropdown list ( for example Tamil Nadu -> Chennai, Salem, Karur and Kerala -> Trivandrum, Kochin etc)

Please help me please how to make it, here i have tried some coding but does not work, Please help me

  • state - Table

$query_state=db_select('state', 's'); $query_state->fields('s',array('State_code','State_name')); $query_state->orderBy('State_name','ASC'); $state_results = $query_state->execute(); $options_state = array();

foreach($state_results as $state_record) { $options_state[$state_record->State_code]=t($state_record->State_name); }

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

City - Table

$query_city=db_select('city', 'c'); $query_city->fields('c',array('District_Code','District_Name')); $query_city->condition('State_Code','$state_record->State_code','='); $query_city->orderBy('District_Name','ASC'); $city_results = $query_city->execute(); $options_city = array();

foreach($city_results as $city_record) { $options_city[$city_record->District_code]=t($city_record->District_Name); }

$form['city']= array('#type' => 'select','#title' => t('District'),'#options' =>$options_city,'#required' => TRUE,'#states'=>array('visible'=>array(':input[name="state"]'=>array('value'=>$options_state))));