The example in this article describes the simple usage of DropDownList in Yii2. Share it with everyone for your reference, the details are as follows:
Here we use practical application as an example to explain the usage of Yii2 DropDownList.
There is a classification table, like Infinitus Classification. The table structure is as follows, pid is the parent classification ID
Here we want to achieve:
When creating a new category, the parent category can be selected from all categories or not selected
When editing a category, the currently edited category cannot be selected as the parent category. . . If you choose yourself, the parent category will be yourself, and something will go wrong!
The implementation code is as follows, I will paste all the code of the form
<?php use common\models\Category; use yii\helpers\ArrayHelper; use yii\helpers\Html; use yii\widgets\ActiveForm; /* @var $this yii\web\View */ /* @var $model common\models\Category */ /* @var $form yii\widgets\ActiveForm */ ?> <div class="category-form"> <div class="row"> <?php if (!$model->isNewRecord) {//如果是编辑分类 $cate = ArrayHelper::map(Category::find()->andWhere('id != :id', [':id' => $model->id])->all(), 'id', 'title'); } else {//如果是新建分类 $cate = ArrayHelper::map(Category::find()->all(), 'id', 'title'); } ?> <div class="col-md-6 col-md-offset-3"> <?php $form = ActiveForm::begin(); ?> <?= $form->field($model, 'title')->textInput(['maxlength' => 100])->label("分类标题") ?> <?= $form->field($model, 'name')->textInput(['maxlength' => 100])->label("分类别名") ?> <?= $form->field($model, 'pid')->dropDownList($cate, ['prompt' => '请选择父分类'])->label("父分类") ?> <?= $form->field($model, 'keywords')->textarea(['maxlength' => 255])->label("分类关键词") ?> <?= $form->field($model, 'description')->textarea(['maxlength' => 255])->label("分类描述") ?> <div class="form-group"> <div class="row"> <div class="col-md-6 col-md-offset-3"> <?= Html::submitButton($model->isNewRecord ? '创建' : '更新', ['class' => $model->isNewRecord ? 'btn btn-block btn-success' : 'btn btn-block btn-primary']) ?> </div> </div> </div> <?php ActiveForm::end(); ?> </div> </div> </div>
Readers who are interested in more Yii-related content can check out the special topics of this site: "Introduction to Yii Framework and Summary of Common Techniques", "Summary of Excellent Development Framework of PHP", "Basic Tutorial for Getting Started with Smarty Templates", "Introduction to PHP Object-Oriented Programming" Tutorial", "php string (string) usage summary", "php+mysql database operation introductory tutorial" and "php common database operation skills summary"
I hope this article will help you design PHP programs based on the Yii framework.