Yii2 实现上下联动的下拉框

首先我先解释下什么是上下联动的下拉框

假如一个view里面有两个select,第一个是公司名,第二个是分公司名。公司有多个,每个公司又有多个分公司,我们实现的就是点击当前公司后,分公司里面显示的事当前公司的分公司。

或者你直接理解成选择所属省份后,下面的select显示的是当前省份的县。

原理

点击第一个select后,执行ajax获取当前公司的分公司,并使用jquery修改分公司内容

两个select的部分视图代码如下


  
  
  1. <?= $form->field($model, 'companies_company_id')->dropDownList(
  2. \yii\helpers\ArrayHelper::map(\backend\models\Companies::find()->all(),'company_id','company_name'),
  3. [
  4. 'prompt'=>'select Company',
  5. 'onchange'=>'
  6. $.post("index.php?r=branches/lists&id='.'"+$(this).val(),function(data){
  7. $("select#departments-branches_branch_id").html(data);
  8. });',
  9. ]
  10. ) ?>
  11.  
  12. <?= $form->field($model, 'branches_branch_id')->dropDownList(
  13. \yii\helpers\ArrayHelper::map(\backend\models\Branches::find()->all(),'branch_id','branch_name'),
  14. [
  15. 'prompt'=>'Select Branches',
  16. ]
  17. ) ?>

list方法代码


  
  
  1. public function actionLists($id)
  2. {
  3. $countBranches = Branches::find()
  4. ->where(['companies_company_id' => $id])
  5. ->count();
  6. $branches = Branches::find()
  7. ->where(['companies_company_id' => $id])
  8. ->all();
  9. if ($countBranches > 0) {
  10. foreach ($branches as $branche) {
  11. echo "<option value='" . $branche->branch_id . "'>" . $branche->branch_name . "</option>";
  12. }
  13. } else {
  14. echo "<option>-</option>";
  15. }
  16. }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值