Yii2 实现无限级联动 [ 2.0 版本 ]
表字段:
id,name,parent
模型添加:
public function getCityList($pid=0)
{
$model = Area::findAll(array('parent'=>$pid));
$arr= ArrayHelper::map($model, 'name', 'id');
$arr=array_merge(['请选择' =>'0'],$arr);
$arr=array_flip($arr);
return $arr;
}
控制器:
public function actionSite($pid=0)
{
$model = new Area();
$model = $model->getCityList($pid);
foreach($model as $value=>$name)
{
echo Html::tag('option',Html::encode($name),array('value'=>$value));
}
}
FORM:
<?=$form->field($model, 'parent')->dropDownList(['1'=>'广东','2'=>'北京'],['style'=>'width:auto','class'=>"form-control link"])?>
JS:
$(function(){
links($('.link'),'Area[parent]');
});
function links(obj,name){
obj.change(function(){
var o=$("select[name='Area[parent]']");
o.attr({"name":''});
obj.attr({"name":name})
obj.nextAll().remove();
if($(this).val()==0)return false;
$.post('?r=area/site&pid='+$(this).val(),function(data){
if(data!='<option value="0">请选择</option>'){
var obc=$("<select>").insertAfter(obj).html(data).addClass('form-control link');
links(obc,name);
}
});
});
}
欢迎指导,提意见。
okokad
注册时间:2016-02-29
最后登录:2017-07-01
在线时长:49小时26分
最后登录:2017-07-01
在线时长:49小时26分
- 粉丝12
- 金钱25
- 威望80
- 积分1315
共 4 条评论
楼主一定要用markdown格式书写,否则会特别乱,我已经帮你修改好了,以后要注意。
好的。谢谢。
dfasd
爱我爱爱爱爱
不错哦不错哦
是吗是那是那么是按是吗
看看我这个合适不,哪里出错了?
`
<label for="community-country_id">地区</label> <div> <?php $countryList = array(); $countryList = ArrayHelper::map(CountryRegion::find()->all(), 'id', 'name'); ?> <select id="community-country_id" class="form-control" name="UserContact[country_id]" style="width:190px;display: inline-block"> <option value="" selected>请选择</option> <?php foreach ($countryList as $key=>$val):?> <option value="<?= $key ?>" <?=$modelContact->country_id != null && $modelContact->country_id == $key?' selected ':'' ?>><?= $val ?></option> <?php endforeach; ?> </select> <?php $provinceList = array(); if ($modelContact->country_id) { $provinceList = ArrayHelper::map(Province::find()->where(['country_id' => $modelContact->country_id])->all(), 'id', 'name'); } ?> <select id="community-province_id" class="form-control" name="UserContact[province_id]" style="width:190px;display: inline-block"> <option value="">请选择</option> <?php foreach ($provinceList as $key=>$val): ?> <option value="<?= $key ?>"<?=$modelContact->province_id != null && $modelContact->province_id == $key?' selected ':'' ?>><?= $val ?></option> <?php endforeach; ?> </select> <?php $cityList = array(); if ($modelContact->province_id) { $cityList = ArrayHelper::map(City::find()->where(['province_id' =>$modelContact->province_id])->all(), 'id', 'name'); } ?> <select id="community-city_id" class="form-control" name="UserContact[city_id]" style="width:180px;display: inline-block"> <option value="">请选择</option> <?php foreach ($cityList as $key=>$val): ?> <option value="<?= $key ?>"<?=$modelContact->city_id != null && $modelContact->city_id == $key?' selected ':'' ?>><?= $val ?></option> <?php endforeach; ?> </select> </div> </div>`