0

I want to add a dropdown list in my page which should show the values from a table column, How can I do this using Yii framework?

I have a table(table name is program) with columns id, program_name, is_active

I have created a new controller and a view associated with it, I need to show a dropdown list in that view with the values populated from program_name

4

2 回答 2

2

I would solve this at model level. e.g.

In Machine model, I would define a getter :

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

And, in your listData :

  Chtml::listData(Machine::model()->with('merk')->findAll(...), 
  'machine_id', 'completeMachineName')
于 2013-01-17T08:44:07.717 回答
1

All you need to do is use CHtml::dropDownList, possibly with CHtml::listData to ease the process of creating a value=>display array for the <options> tag.

Example (see comments in code):

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
);

Edit Incase you don't have a CActiveRecord model for program table, you could use direct sql, replace Program::model()->findAll() in the above sample with:

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

Also if you want to use program_name column values as the value attribute for the option tag, then you can use:

CHtml::listData($data,'program_name','program_name') // replaced the 'id' with 'program_name'
于 2013-01-17T10:10:58.693 回答