Optgroup drop-downs with Yii

Sometimes frameworks make things simple and just work so well you want to kick yourself for having written it out the long way first. A recent example is where I had to use optgroups for an HTML drop-down and didn’t even think to check the Yii spec to see if it could do this for me. Turns out it can and is super-simple:

listData(array $models, string $valueField, string $textField, string $groupField='')

You simply pass the field name of the group field as the 4th argument of the listData function, and add that field to the query if need be. A lot easier to write and maintain than a complex do/while loop.

One Response to “ “Optgroup drop-downs with Yii”

  1. jebin says:

    id parent_id cat_name
    1 o aptitude
    10 0 technical
    2 1 arithmetic
    3 2 trainsprob
    4 1 logical
    5 1 verbal

    i need to retrieve data in the format of dropdownlist with opt option…


    i should only select the values in the lower level.. i mean can only select trainsprob in the above example.

Leave a Reply