2017-03-23 4 views
0

Ich folgte einem Youtube Tutorial, um eine abhängige DropDownList (State und City) zu erstellen, und bald nach dem Laden zeigt die Dropdownliste City alle Städte an.Yii2 abhängige DropDownList Zustand und Stadt

Ich wünschte, keine wurden angezeigt, nur bei der Auswahl eines Staates. Aber ich bin mir nicht sicher, wie es geht, und hätte gerne Hilfe.

Schau, wie ich getan habe:

VIEW: _search.php

<?php $form = ActiveForm::begin([ 
    'action' => ['index'], 
    'method' => 'get', 
]); ?> 

<?= $form->field($model,'state_id')->dropDownList(
       ArrayHelper::map(State::find()->all(), 'id', 'nome'), 
       [ 
        'prompt'=>'Selecione', 
        'onchange'=>' 
        $.get("'.Url::toRoute('/city/lists').'", { id: $(this).val() }) 
         .done(function(data) { 
          $("#'.Html::getInputId($model, 'city_id').'").html(data); 
         } 
        );'  
       ]); 
?> 

<?= $form->field($model,'city_id')->dropDownList(
       ArrayHelper::map(City::find()->all(), 'id', 'name'), 
       [ 
        'prompt'=>'Selecione o estado', 
       ]); 
?> 

REGLER: CityController.php

public function actionLists($id) 
{ 
    $countCity = City::find() 
      ->where(['state_id' => $id]) 
      ->count(); 

    $cities = City::find() 
      ->where(['state_id' => $id]) 
      ->all(); 

    if($countCity > 0) 
    { 
     foreach($cities as $city){ 
      echo "<option value='".$city->id."'>".$city->name."</option>"; 
     } 
    } 
    else{ 
     echo "<option> - </option>"; 
    } 

} 

SQL:

CREATE TABLE `city` (
    `id` int(11) NOT NULL, 
    `name` varchar(250) COLLATE utf8_unicode_ci DEFAULT NULL, 
    `state_id` int(11) DEFAULT NULL, 
    `population_2010` int(11) DEFAULT NULL, 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; 

-- -------------------------------------------------------- 

CREATE TABLE `state` (
    `id` int(11) NOT NULL, 
    `name` varchar(250) COLLATE utf8_unicode_ci DEFAULT NULL, 
    `sigla` varchar(250) COLLATE utf8_unicode_ci DEFAULT NULL 
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci; 

Antwort

1

diesen Code hinzufügen, in auf (Ändern)

$.get("'.Url::toRoute('/city/lists').'", { id: $(this).val() }) 
        .done(function(data) { 
         $("select#selectid").html(data); 
        } 
       );' 




       <select id="selectid"></select> 

und Sie müssen zurückkehren Optionswert von

actionList($id){ 
           $list=Model::findBySql('your quer where id=$id')->all() 
      foreach($list as $l){ echo "<option value='" $l->id."'>'.$l->name.'</option>'; 
       } 

ich Ihnen empfehlen dieses Video

https://m.youtube.com/watch?v=bpj7dF2orbI

+0

Hallo, zu sehen auf Suchseite funktioniert gut, aber auf Profilseite wird nicht gespeichert. – gugoan

+0

Entschuldigung, ich habe Sie nicht bekommen, zeigen Sie bitte Ihren Code – Dipendra