当前位置:Gxlcms > php框架 > Yii2实现上下联动下拉框功能的方法

Yii2实现上下联动下拉框功能的方法

时间:2021-07-01 10:21:17 帮助过:34人阅读

本文实例讲述了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. <?= $form->field($model, 'branches_branch_id')->dropDownList(
  12. \yii\helpers\ArrayHelper::map(\backend\models\Branches::find()->all(),'branch_id','branch_name'),
  13. [
  14. 'prompt'=>'Select Branches',
  15. ]
  16. ) ?>

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. }

更多关于Yii相关内容感兴趣的读者可查看本站专题:《Yii框架入门及常用技巧总结》、《php优秀开发框架总结》、《smarty模板入门基础教程》、《php面向对象程序设计入门教程》、《php字符串(string)用法总结》、《php+mysql数据库操作入门教程》及《php常见数据库操作技巧汇总》

希望本文所述对大家基于Yii框架的PHP程序设计有所帮助。

人气教程排行