Yii Dropdownlist - 显示表中的列值

时间:2013-01-17 08:36:56

标签: php yii

我想在我的页面中添加一个下拉列表,该列表应显示表列中的值,如何使用Yii框架执行此操作?

我有一个表(表名是程序)和列 id,program_name,is_active

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

2 个答案:

答案 0 :(得分:2)

我会在模型级解决这个问题。 e.g。

在机器模型中,我会定义一个getter:

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

并且,在listData中:

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

答案 1 :(得分:1)

您需要做的只是使用CHtml::dropDownList,可能使用CHtml::listData来简化为<options> tag创建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
);

修改如果 program 表没有CActiveRecord模型,您可以使用direct sql,替换Program::model()->findAll()在上面的示例中:

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

此外,如果您想将 program_name 列值用作value标记的option属性,则可以使用:

CHtml::listData($data,'program_name','program_name') // replaced the 'id' with 'program_name'
相关问题