The example in this article describes how Yii2 implements the up-and-down linkage drop-down box function. Share it with everyone for your reference, the details are as follows:
First of all, let me explain what is a drop-down box with up and down linkage
If there are two selections in a view, the first one is the company name, and the second one is the branch name. There are multiple companies, and each company has multiple branches. What we achieve is that after clicking on the current company, the branches displayed in the branches are the branches of the current company.
Or you can directly understand that after selecting the province, the selection below displays the counties of the current province.
Principle:
After clicking the first select, execute ajax to get the branch of the current company, and use jQuery to modify the branch content
The partial view code of the two selects is as follows:
<?= $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 method code :
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>"; } }
I hope this article will be helpful to everyone’s PHP program design based on the Yii framework.
For more related articles on how Yii2 implements the up-down linkage drop-down box function, please pay attention to the PHP Chinese website!