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 explainWhat is an up-down linkage drop-down box
Suppose there are two choices in a view, the first is the company name, and the second 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 select 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 content of the branch
Part of the view code for 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>"; } }
Readers who are interested in more Yii-related content can check out the special topics on this site: "Introduction to Yii Framework and Summary of Common Techniques", "Summary of Excellent PHP Development Framework", "Basic Tutorial for Getting Started with Smarty Templates", "Introduction to PHP Object-Oriented Programming" Tutorial", "php string usage summary", "php+mysql database operation introductory tutorial" and "php common database operation skills summary"
I hope this article will be helpful to everyone’s PHP program design based on the Yii framework.