Search code examples
yii-extensionsyiiyii-components

How to select a column of data from table with WHERE closure and display


How to select a column of data from table with WHERE closure and list as combo-box in yii?


Solution

  • Have a look at the CHtml methods dropDownList() and activeDropDownList().

    You can set the data you insert into the dropdownlist to be the results from an active record query, for example;

    echo CHtml::dropDownList('myDropdown', '1',  CHtml::listData(myModel::model()->findAllByAttributes(array('myField'=>1)),'id','name'));
    

    The above command would select all the results from the myModel model where myField = 1 (using their 'id' as the value and their 'name' as the displayed text) and insert them into a dropdownlist with name 'myDropdown' and the initial selected value would be 1.

    If you're using this in a form, for example created by gii, then you can use the $form to create the dropdown. This actually uses activeDropDownList(), so the syntax is a little different, here's an example:

     echo $form->dropDownList($model,'myOtherField', CHtml::listData(myModel::model()->findAllByAttributes(array('myField'=>1)),'id','name'));
    

    the bit that's actually populating the dropdownlist with the data from the active record query is the CHtml::listData() method which is taking a result set from the active record query and formatting it into an array that will be accepted into the $data param in dropDownList() or activeDropDownList().