view中代码
<?php use yii\bootstrap\ActiveForm; /* @var $this yii\web\View */ /* @var $form yii\bootstrap\ActiveForm */ ?> <?php $form = ActiveForm::begin(['enableClientValidation' => false]);?> <?= $form->field($model,'province')->dropDownList($model->getCityList(0), [ 'prompt'=>'--请选择省--', 'onchange'=>' $(".form-group.field-member-area").hide(); $.post("'.yii::$app->urlManager->createUrl('member/site').'?typeid=1&pid="+$(this).val(),function(data){ $("select#member-city").html(data); });', ]) ?> <?= $form->field($model, 'city')->dropDownList($model->getCityList($model->province), [ 'prompt'=>'--请选择市--', 'onchange'=>' $(".form-group.field-member-area").show(); $.post("'.yii::$app->urlManager->createUrl('member/site').'?typeid=2&pid="+$(this).val(),function(data){ $("select#member-area").html(data); });', ]) ?> <?= $form->field($model, 'area')->dropDownList($model->getCityList($model->city),['prompt'=>'--请选择区--',]) ?> <?php ActiveForm::end();?>model中添加下面的函数
/** * @param $pid * @return array */ public function getCityList($pid) { $model = City::findAll(array('pid'=>$pid)); return ArrayHelper::map($model, 'id', 'name'); }控制器中添加下面的代码:
/** * Function output the site that you selected. * @param int $pid * @param int $typeid */ public function actionSite($pid, $typeid = 0) { $model = new Member(); $model = $model->getCityList($pid); if($typeid == 1){$aa="--请选择市--";}else if($typeid == 2 && $model){$aa="--请选择区--";} echo Html::tag('option',$aa, ['value'=>'empty']) ; foreach($model as $value=>$name) { echo Html::tag('option',Html::encode($name),array('value'=>$value)); } }City数据库结构:
/* Navicat MySQL Data Transfer Source Server : MySQL Source Server Version : 50624 Source Host : localhost:3306 Source Database : yii2advanced Target Server Type : MYSQL Target Server Version : 50624 File Encoding : 65001 Date: 2015-07-13 14:27:12 */ SET FOREIGN_KEY_CHECKS=0; -- ---------------------------- -- Table structure for yii2_city -- ---------------------------- DROP TABLE IF EXISTS `yii2_city`; CREATE TABLE `yii2_city` ( `id` smallint(5) unsigned NOT NULL AUTO_INCREMENT, `pid` smallint(5) unsigned NOT NULL DEFAULT '0', `name` varchar(120) NOT NULL DEFAULT '', PRIMARY KEY (`id`), KEY `parent_id` (`pid`) ) ENGINE=MyISAM AUTO_INCREMENT=3410 DEFAULT CHARSET=utf8;
- 本文固定链接: https://zxbcw.cn/post/4050/
- 转载请注明:必须在正文中标注并保留原文链接
- QQ群: PHP高手阵营官方总群(344148542)
- QQ群: Yii2.0开发(304864863)