SoFunction
Updated on 2025-04-04

Example of simple usage of DropDownList in Yii2

This article describes the simple usage of DropDownList in Yii2. Share it for your reference, as follows:

Here we will explain the usage of Yii2 DropDownList using practical applications as an example.

There is a classification table, which is the Infinitus classification type, and the table structure is as follows, and the pid is the parent classification ID
Here we want to implement:

When creating a new category, the parent category can choose one or not from all categories.

When editing a category, the parent category cannot select the currently edited category. . . If you choose yourself, your father’s classification is yourself, and there will inevitably be a mistake!

The implementation code is as follows, I will post all the codes of 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) {//If it is an edit category      $cate = ArrayHelper::map(Category::find()->andWhere('id != :id', [':id' => $model->id])->all(), 'id', 'title');
    } else {//If it is a new category      $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("Category Title") ?>
      <?= $form->field($model, 'name')->textInput(['maxlength' => 100])->label("Category Name") ?>
      <?= $form->field($model, 'pid')->dropDownList($cate, ['prompt' => 'Please select the parent category'])->label("Parent Classification") ?>
      <?= $form->field($model, 'keywords')->textarea(['maxlength' => 255])->label("Category Keywords") ?>
      <?= $form->field($model, 'description')->textarea(['maxlength' => 255])->label("Category Description") ?>
      <div class="form-group">
        <div class="row">
          <div class="col-md-6 col-md-offset-3">
            <?= Html::submitButton($model->isNewRecord ? 'create' : 'renew', ['class' => $model->isNewRecord ? 'btn btn-block btn-success' : 'btn btn-block btn-primary']) ?>
          </div>
        </div>
      </div>
      <?php ActiveForm::end(); ?>
    </div>
  </div>
</div>

For more information about Yii, readers who are interested in this site can view the topic:Yii framework introduction and common techniques summary》、《Summary of excellent development framework for php》、《Basic tutorial on getting started with smarty templates》、《PHP object-oriented programming tutorial》、《Summary of usage of php strings》、《PHP+mysql database operation tutorial"and"Summary of common database operation techniques for php

I hope that this article will be helpful to everyone's PHP programming based on the Yii framework.