本文實例講述了Yii2實現上下聯動下拉框功能的方法。分享給大家供大家參考,具體如下:
首先我先解釋下什么是上下聯動的下拉框
假如一個view里面有兩個select,第一個是公司名,第二個是分公司名。公司有多個,每個公司又有多個分公司,我們實現的就是點擊當前公司后,分公司里面顯示的事當前公司的分公司。
或者你直接理解成選擇所屬省份后,下面的select顯示的是當前省份的縣。
原理:
點擊第一個select后,執行ajax獲取當前公司的分公司,并使用jQuery修改分公司內容
兩個select的部分視圖代碼如下:
<?= $form->field($model, 'companies_company_id')->dropDownList( /yii/helpers/ArrayHelper::map(/backend/models/Companies::find()->all(),'company_id','company_name'), [ 'prompt'=>'select Company', 'onchange'=>' $.post("index.php?r=branches/lists&id='.'"+$(this).val(),function(data){ $("select#departments-branches_branch_id").html(data); });', ]) ?><?= $form->field($model, 'branches_branch_id')->dropDownList( /yii/helpers/ArrayHelper::map(/backend/models/Branches::find()->all(),'branch_id','branch_name'), [ 'prompt'=>'Select Branches', ]) ?>list方法代碼:
public function actionLists($id){ $countBranches = Branches::find() ->where(['companies_company_id' => $id]) ->count(); $branches = Branches::find() ->where(['companies_company_id' => $id]) ->all(); if ($countBranches > 0) { foreach ($branches as $branche) { echo "<option value='" . $branche->branch_id . "'>" . $branche->branch_name . "</option>"; } } else { echo "<option>-</option>"; }}
希望本文所述對大家基于Yii框架的PHP程序設計有所幫助。
新聞熱點
疑難解答
圖片精選