phpyiiyii-chtml

How to make a dropDownList in Yii?


I have 2 attributes in model jobs, they are tag and category, I want to make a dropDownList that display the value of tag who have category equal 'salary', here is my code:

$s= CHtml::listData($model2, 'salary', 'tag');                         
echo CHtml::dropDownList('salary', 'salary', $s);

my db:

tag / category

1 / val1

2 / val1

a / val2

1000 / salary

2000 / salary

but I got a dropDownList that contains only the last value who have these conditions. what is the wrong in my code?


Solution

  • There are two reasons why you can get only one results, firstly the number of results you get in $model2 affects the results, check if your are using findAll to return the all the rows matching a condition and not find and findByPk as they return only one value,

    Secondly the second attribute of listData should be your value field 'salary' is not an attribute of the model, this has to be the valueField(see this).

    It will remain same if it assigned as salary - a constant value for all option elements, meaning your array will be overwritten for each reach leaving you with the array of one element containing the last value.

    You should 'tag_id'/'id' or some sort of primary key from your model or tag value( assuming it is unique) to identify the tag by

    $model2 = MyModel::model()->findAll("category = salary");
    $s= CHtml::listData($model2, 'tag', 'tag');                         
    echo CHtml::dropDownList('salary', 'salary', $s,array('empty'=>'--Select--'));