Home>

Here is a practical application to explain the use of yii2 dropdownlist.

There is a classification table,Infinite pole classification,The table structure is as follows,pid is the parent category 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 parent category cannot select the currently edited category.. . If you choose yourself,The parent classification is itself,Bound to 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>
  <div>
    <?php
    if (! $model->isnewrecord) {//if editing 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>
      <?php $form=activeform ::begin ();?>
      <?= $form->field ($model, "title")->textinput (["maxlength" =>100])->label ("category title")?>
      ?= $form->field ($model, "name")->textinput (["maxlength" =>100])-&label ("class alias")?>
      <?= $form->field ($model, "pid")->dropdownlist ($cate, ["prompt" =>"Please select parent category"])->label (" Parent category ")?>
      <?= $form->field ($model, "keywords")->textarea (["maxlength" =>255])->label ("Classification Keywords")? ;>
      <?= $form->field ($model, "description")->textarea (["maxlength" =>255])->label ("category description")?>
      <div>
        <div>
          <div>
            <?= html ::submitbutton ($model->isnewrecord?"Create":"Update", ["class" =>$model->isnewrecord?" -block btn-success ":" btn btn-block btn-primary "])?>
          </div>
        </div>
      </div>
      <?php activeform ::end ();?>
    </div>
  </div>
</div>
php
  • Previous Yii2 simple method to add verification code to the form
  • Next Summary of methods for generating image verification codes in PHP (2 methods)