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 category ID
Here we have to implement:
When creating a new category, the parent category can be selected from all categories or not
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>
I hope this article will be helpful to everyone’s PHP program design based on Yii framework.
For more articles related to simple usage examples of DropDownList in Yii2, please pay attention to the PHP Chinese website!