CHtml::listData does not work with DAO?

Hi, I am new to Yii. After 2 days trying, I am still stuck in the listData. Hope anyone can help out of the problem.

I want to display a dropdown list with the value selected from db. And I am building my db with DAO.

In short, this is my select statement:





class dbAdmin

{    public static function selectDept(){

        $conn = Yii::app()->db;

        $sql = "select deptid, deptname from eg_dept order by deptid";

        return $conn->createCommand($sql)->queryColumn();

    }

}




when I var_dump() the above returned value, i can see the result:





array(2) { [0]=> string(3) "FIANCE" [1]=> string(3) "HR" }




however, when i tried to use the listData function, the output is null:





        $depts = dbAdmin::selectDept();

        $model->dept_list = CHtml::listData($depts, 'id', 'name');

        var_dump($model->dept_list);




output:





array(1) { [""]=> NULL } 




all I saw in the discussions are using ActiveRecord, but in my case, I can only use the DAO method. Could it be the reason why the listData can’t generate the correct output?

Check the documentation for listData - http://www.yiiframework.com/doc/api/1.1/CHtml#listData-detail

And check the source code of it (click on show)

You will see that listData works only with ActiveRecords as for the first parameter it expects an array of models…

and what listData does is that it generates an array of values that you already have by using DAO and that you saw with var_dump()… .so you don’t need to call listData at all

Thanks mdomba.

Correct me if I get it wrongly, I thought listData can help to re-organize the array I get from the DB to something like array(‘Finanace’=>‘Finance’, ‘HR’=>‘HR’), instead of array(‘0’=>‘Finance’, ‘1’=>‘HR’).

Now I use a "manual" way to achieve this:





        $depts = dbAdmin::selectDept();

        foreach($depts as $value){

            $this->dept_list[$value] = $value;

        }



and need to correct a mistake of the sql statement I post in the #1 reply:




        $sql = "select deptid from eg_dept order by deptid";



As I wrote above… check the source of listData… it’s easy from the API doc… you will see that list Data does this


$listData[$value]=$text;

value is the second parameter

text is the third parameter

and you are sending "id" as second parameter and "name" as third…

Anyway there is no other way… if you use DAO… you get an array of values… and you cannot use listData…