Yii2使用dropdownlist实现地区三级联动功能的方法
本文实例讲述了Yii2使用dropdownlist实现地区三级联动功能的方法。分享给大家供大家参考,具体如下:
视图部分:
<?php useyii\helpers\Url; useyii\widgets\ActiveForm; useyii\helpers\ArrayHelper; useyii\helpers\Html; /*@var$thisyii\web\View*/ /*@var$modelcommon\search\service\ItemSearch*/ /*@var$formyii\widgets\ActiveForm*/ ?> <divclass="row"> <divclass="item-search"> <?php$form=ActiveForm::begin([ 'action'=>['index'], 'method'=>'get', 'options'=>['class'=>'form-inline'] ]);?> <?=$form->field($model,'cityName',['options'=>['class'=>'form-groupcol-lg-2']])->dropDownList(ArrayHelper::map($cities,'id','name'),['prompt'=>'请选择城市'])->label('请选择城市',['class'=>'sr-only'])?> <?=$form->field($model,'areaName',['options'=>['class'=>'form-groupcol-lg-2']])->dropDownList(ArrayHelper::map($areas,'id','name'),['prompt'=>'请选择区县'])->label('请选择区县',['class'=>'sr-only'])?> <?=$form->field($model,'communityName',['options'=>['class'=>'form-groupcol-lg-2']])->dropDownList(ArrayHelper::map($communities,'id','name'),['prompt'=>'请选择小区'])->label('请选择小区',['class'=>'sr-only'])?> <divclass="col-lg-2col-lg-offset-1"> <inputclass="form-control"id="keyword"placeholder="请输入小区名"value=""/> </div> <divclass="col-lg-1"> <buttontype="button"id="search-community"class="btnbtn-info">搜索</button> </div> <p></p> <divclass="form-groupcol-lg-1pull-right"> <?=Html::submitButton('搜索',['class'=>'btnbtn-primary'])?> </div> <?phpActiveForm::end();?> </div> </div> <p> </p> <?php $this->registerJs(' //市地址改变 $("#itemsearch-cityname").change(function(){ //市id值 varcityid=$(this).val(); $("#itemsearch-areaname").html("<optionvalue=\"0\">请选择区县</option>"); $("#itemsearch-communityname").html("<optionvalue=\"0\">请选择小区</option>"); if(cityid>0){ getArea(cityid); } }); //区地址改变 $("#itemsearch-areaname").change(function(){ //区id值 varareaid=$(this).val(); $("#itemsearch-communityname").html("<optionvalue=\"0\">请选择小区</option>"); if(areaid>0){ getCommunity(areaid); } }); //获取市下面的区列表 functiongetArea(id) { varhref="'.Url::to(['/service/base/get-area-list'],true).'"; $.ajax({ "type":"GET", "url":href, "data":{id:id}, success:function(d){ $("#itemsearch-areaname").append(d); } }); } //获取区下面的小区列表 functiongetCommunity(id) { varhref="'.Url::to(['/service/base/get-community-list'],true).'"; $.ajax({ "type":"GET", "url":href, "data":{id:id}, success:function(d){ $("#itemsearch-communityname").append(d); } }); } //搜索小区 $("#search-community").click(function(){ varword=$("#keyword").val(); varareaid=$("#itemsearch-areanameoption:selected").val(); varhref="'.Url::to(['/service/base/search-community'],true).'"; if(areaid>0){ $.ajax({ "type":"GET", "url":href, "data":{id:areaid,word:word}, success:function(d){ $("#itemsearch-communityname").html(d); } }); } }); '); ?>
模型部分:
就是我们常用的ajax请求,当然php中需要直接组合成<optionvalue=""></option>这样的结构直接用,$form->field($model,$var)中的变量数据表中不一定有,得在模型中自己定义,并设置安全字段,而且搜索模型也可能需要修改成自己需要的样子,模型可能要这样:
classHuangYeErrorextends\yii\db\ActiveRecord { public$cityName; public$areaName; public$communityName; public$group; public$cate; /** *@inheritdoc */ publicstaticfunctiontableName() { return'll_hy_huangye_error'; } publicstaticfunctiongetDb() { returnYii::$app->get('dbnhuangye'); } }
之前是多表,需要使用jjoinWith()连表,后来被我全部转化为单表了,多表实在是慢,能转化成单表就用单表吧:
classHuangYeErrorSearchextendsHuangYeError { constPAGE_SIZE=20; public$communityName; public$startTime; public$endTime; /** *@inheritdoc */ publicfunctionrules() { return[ [['id','serviceid','userid','categoryid','communityid','sortorder','ctime','utime','status'],'integer'], [['username','name','logo','phone','address','content','error','communityName','startTime','endTime'],'safe'], ]; } /** *@inheritdoc */ publicfunctionscenarios() { //bypassscenarios()implementationintheparentclass returnModel::scenarios(); } /** *Createsdataproviderinstancewithsearchqueryapplied * *@paramarray$params * *@returnActiveDataProvider */ publicfunctionsearch($params) { $query=HuangYeError::find(); //status==9删除状态 $condition='`status`!=:status'; $p[':status']=9; $query->where($condition,$p); $dataProvider=newActiveDataProvider([ 'query'=>$query, 'pagination'=>[ 'pageSize'=>self::PAGE_SIZE, ], ]); $this->load($params); if(!$this->validate()){ //uncommentthefollowinglineifyoudonotwanttoanyrecordswhenvalidationfails //$query->where('0=1'); return$dataProvider; } $query->andFilterWhere([ 'userid'=>$this->userid ]); $query->andFilterWhere(['like','username',$this->username]) ->andFilterWhere(['like','name',$this->name]) ->andFilterWhere(['like','phone',$this->phone]) ->andFilterWhere(['like','address',$this->address]) ->andFilterWhere(['like','content',$this->content]) ->andFilterWhere(['ll_hy_huangye_error.status'=>$this->status]) ->andFilterWhere(['ll_hy_huangye_error.categoryid'=>$this->categoryid]) ->andFilterWhere(['between','ctime',strtotime($this->startTime.'0:0:0'),strtotime($this->endTime.'23:59:59')]) ->andFilterWhere(['like','error',$this->error]); if(intval($this->communityName)){ $query->andFilterWhere(['ll_hy_huangye_error.communityid'=>intval($this->communityName)]); } $order='`ctime`DESC'; $query->orderBy($order); return$dataProvider; } }
控制器中写比较简单一点,直接调用就行了:
/** *ajax请求小区 * *@param$id *@returnstring */ publicfunctionactionGetCommunityList($id) { $option=''; $result=self::getCommunity($id); if($result){ foreach($resultas$value){ $option.='<optionvalue="'.$value['id'].'">'.$value['name'].'</option>'; } }else{ $option.='<optionvalue="0">暂未开通可选择的小区</option>'; } echo$option; }
更多关于Yii相关内容感兴趣的读者可查看本站专题:《Yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》
希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。