I need to display country name in a select filed and display its city names in another select field according to selection change committed on country name field. i am using ajax for selection change event. This is what i have done so far. now i need to fetch city names from second api corresponding to the country name in the select field.
public function getFormId() { return 'newmoduleform_ajax_form'; } public function buildForm(array $form, FormStateInterface $form_state) { // First API Call to populate country select field $result = []; $country_options = []; $client = Drupal::httpClient(); // Fetch API values. $request = $client->request('GET','https://restcountries.com/v2/all'); $result = Json::decode($request->getBody()->getContents()); foreach ($result as $item) { $country_options[] = $item['name']; } if (empty($form_state->getValue('country_dropdown'))) { // Use a default value. $selected_option = key($country_options); } else { // Get the value if it already exists. $selected_option = $form_state->getValue('country_dropdown'); } $form['option_country_fieldset'] = [ '#type' => 'fieldset', ]; $form['option_country_fieldset']['country_dropdown'] = [ '#type' => 'select', '#title' => $this->t('country'), '#options' => $country_options, // Bind an Ajax callback to the element. '#ajax' => [ 'callback' => '::instrumentDropdownCallback', 'wrapper' => 'state-fieldset-container', 'event' => 'change', ], ]; $form['select_fieldset_container'] = [ '#type' => 'container', '#attributes' => ['id' => 'state-fieldset-container'], ]; $form['select_fieldset_container']['select_fieldset'] = [ '#type' => 'fieldset', ]; $form['select_fieldset_container']['select_fieldset']['select_dropdown'] = [ '#type' => 'select', '#title' => $this->t('Country Name-'). ' ' . $country_options[$selected_option], '#options' => static::getSecondDropdownOptions(), ]; return $form; } public function submitForm(array &$form, FormStateInterface $form_state) { } public function instrumentDropdownCallback(array $form, FormStateInterface $form_state) { return $form['select_fieldset_container']; } public static function getSecondDropdownOptions() { [![second api that have city name][1]][1] $result_second = []; $city_options = []; $client = Drupal::httpClient(); // Fetch API values. $request = $client->request('GET','https://countriesnow.space/api/v0.1/countries'); $result_second = Json::decode($request->getBody()->getContents()); foreach ($result_second[data] as $item_second) { // what to do here } // what to do here }