Yii下拉列表—显示表中的列值


Yii Dropdownlist - showing the column values from a table

我想在我的页面中添加一个下拉列表,应该显示从表列的值,我如何使用Yii框架做到这一点?

我有一个表(表名是程序)与列Id, program_name, is_active

我已经创建了一个新的控制器和与之关联的视图,我需要在该视图中显示一个下拉列表,其中包含从program_name
填充的值。

我会在模型级别解决这个问题。例如

在Machine模型中,我将定义getter:

 public function getCompleteMachineName ()
 {
  return $this->merk->name.' '.$this->name;
 }

并且,在listData中:

  Chtml::listData(Machine::model()->with('merk')->findAll(...), 
  'machine_id', 'completeMachineName')

您所需要做的就是使用CHtml::dropDownList,可能使用CHtml::listData来简化为<options>标记创建value=>display数组的过程。

示例(参见代码中的注释):

echo CHtml::dropDownList(
     'somename',// for "name" attribute of <select> html tag,
                // this also becomes the "id" attribute, incase you don't specify
                // it explicitly in the htmlOptions array
     '', // the option element that is to be selected by default
     CHtml::listData( // listData helps in generating the data for <option> tags
        Program::model()->findAll(), // a list of model objects. This parameter
              // can also be an array of associative arrays
              // (e.g. results of CDbCommand::queryAll).
        'id', // the "value" attribute of the <option> tags, 
              // here will be populated with id column values from program table 
        'program_name' // the display text of the <option> tag,
              // here will be populated with program_name column values from table
     ),
     array('id'=>'someid'), // the htmlOptions array, whose values will be
              // generated as html attributes of <select> and <option> tags
);

编辑如果您没有程序表的CActiveRecord模型,可以使用直接sql,将上面示例中的Program::model()->findAll()替换为:

Yii::app()->db->createCommand()->select('id, program_name')->from('program')->queryAll()

如果您想使用program_name列值作为option标记的value属性,那么您可以使用:

CHtml::listData($data,'program_name','program_name') // replaced the 'id' with 'program_name'