表单之下拉菜单——Yii2框架(Ⅲ)

0x00 概述

以图书管理系统为例,在提交表单时,有时需要选择性别或者类别等,可以通过下拉菜单满足的功能,查阅相关资料后,找到了这个功能的使用方法。

0x01 应用例子

管理系统中使用了yii表单生成器生成的方法。
在controller中需要拿到数据,使用findall或者all方法。

public function actionIndex()
{
    $model = new UserModel();
    $data = Category::find()->asArray()->all();
    return $this->render('query', ['model' => $model,'data'=>$data,]);
}   

在View中,使用表单生成器。

<?= $form->field($model, 'categoryid')->dropDownList(ArrayHelper::map($data,'categoryid', 'category'),['prompt' => '请选择类别'])->label("类别"); ?>

hint:

dropDownList           --->     yii2.0  下拉列表的方法
ArrayHelper::map()     --->     构建一个(key => value) 的一维或多维数组
$data               --->     数据源
id                  --->     option 的 value 值
customer_name       --->     option 标签的 值

提交的form中是ID值。

如果固定选项列表。参考如下:

<?= $form->field($model, 'cardname')->dropDownList(ArrayHelper::map(
  [
    0=>[ 'cardnameid'=>'一卡通','cardname'=>'一卡通' ], 
    1=>['cardnameid'=>'身份证','cardname'=>'身份证'],
  ],
    'cardnameid', 'cardname'))->label("证件类型"); ?>

0x02 扩展方法

Updated At: Author:xmsec
Chief Water dispenser Manager of Lancet, delivering but striving.
Github
comments powered by Disqus