yii在form中使用dropdownlist

在一个form中希望使用yii构造的dropdownlist,generator生成的_form.php还是有很多不能符合要求的地方。

特别是dropdownlist由一个表保存着数据的时候。

接下来看看代码如何实现。

在UserController.php的actionCreate中需要使用到一个type表中的分类信息

public function actionCreate()
    {
        $model=new User;
        //创建一个Type的model
        $type_model = new Type;
        $type_list = array();
        //获取所有的分类信息的id&name字段数据
        foreach($type_list ->findAll(array("select"=>"id, name")) as $_model) {
        //保存成为一个数组
            $type_list [$_model->attributes['id']] = $_model->attributes['name'];
        }
        
        ...

        $this->render('create',array(
            'model'=>$model,
            //传递数据给view
            'type_list ' =>$type_list 
        ));
    }

在create.php这个view中,自动生成的是调用了一个render Form的方法,将Controller中获得type_list传递给render方法

<?php $this->renderPartial('_form', array('model'=>$model,'type_list' =>$type_list)); ?>

在_form.php这个生成form的模板中

<?php
//传递给dropDownList方法type_list的值, type_id是在User表中的字段,保证提交之后,这个值是写入到type_id这个字段里面的
 echo $form->dropDownList($model, 'type_id', $type_list);

 ?>

以上三步,即可以在一个创建用户的表单中,使用到用户分类表中的所有数据用于填充用户数据!

个人认为,一开始还是算比较复杂的。但是反过来看,只有几行代码即完成了从数据库的某个表中获取数据并渲染成html代码,还是很方便的。

如果Type的这个方法用的比较多,可以考虑将生成数组的方法封装到Type的model类中,变成类方法,而且还可以缓存结果,减少数据库的反复读写!

原文地址:https://www.cnblogs.com/leftice/p/3779037.html