依赖下拉yii2.怎么做?
发布时间:2020-12-14 00:51:27 所属栏目:百科 来源:网络整理
导读:我可以在yii2中创建依赖下拉列表吗? 我有两张桌子: 'id','name_country"'id','name_city','country_id' 我的模型中有两种方法: public function getCountryList(){$models = NetCountry::find()-asArray()-all();return ArrayHelper::map($models,'id','c
我可以在yii2中创建依赖下拉列表吗?
我有两张桌子: 'id','name_country" 'id','name_city','country_id' 我的模型中有两种方法: public function getCountryList() { $models = NetCountry::find()->asArray()->all(); return ArrayHelper::map($models,'id','country_name'); } 和 public function getCityList($parent_id) { $models = commonmodelsCity::find()->where(['parent_id' => $country_id])->asArray()->all(); return ArrayHelper::map($models,'country_id'); } 我有第一个字段: <?= $form->field($model,'country')->dropDownList($model->countryList),['id'=>'parent_id']; 第二个 <?= $form->field($model,'city')->dropDownList($model->cityList); 我需要’传递’parent_id到控制器并通过AJAX(使用JSON)返回city_list. 我怎样才能做到这一点?我看到an example in Yii1,但是Yii2怎么样?
使用krajee扩展来依赖下拉
细节在这里Krejee dependent dropdown for yii2 或按照以下说明操作: 通过composer安装扩展: $php composer.phar require kartik-v/dependent-dropdown "dev-master" 在你看来: use kartikwidgetsDepDrop; // Normal parent select echo $form->field($model,'cat')->dropDownList($catList,['id' => 'cat-id']); // Dependent Dropdown echo $form->field($model,'subcat')->widget(DepDrop::classname(),[ 'options' => ['id' => 'subcat-id'],'pluginOptions' => [ 'depends' => ['cat-id'],'placeholder' => 'Select...','url' => Url::to(['/site/subcat']) ] ]); //控制器 public function actionSubcat() { $out = []; if (isset($_POST['depdrop_parents'])) { $parents = $_POST['depdrop_parents']; if ($parents != null) { $cat_id = $parents[0]; $out = self::getSubCatList($cat_id); // the getSubCatList function will query the database based on the // cat_id and return an array like below: // [ // ['id'=>'<sub-cat-id-1>','name'=>'<sub-cat-name1>'],// ['id'=>'<sub-cat_id_2>','name'=>'<sub-cat-name2>'] // ] echo Json::encode(['output'=>$out,'selected'=>'']); return; } } echo Json::encode(['output'=>'','selected'=>'']); } (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |