Warning: Use of undefined constant yes - assumed 'yes' (this will throw an Error in a future version of PHP) in /homepages/26/d285632327/htdocs/ on line 1

Yii2 dropdown select optgroup

  • Sumo

I have struggled a lot, while figuring this out. Now I want to share what I managed to do.

Situation: We have posts, and categories, each post attached to one category. Categories have 2 levels: parent and child. Post can be attached to child category only.

Problem: Get the select dropdown box of categories with optgourp grouppings.


yii2 optgroup select dropdown


yii\helpers\ArrayHelper::map() didn’t work for me, it broke the multi-dimentional array structure and showed a blank select box.

And that’s why I wrote a helper function in the Category Model file, that returns the list of categories as a array of arrays. Assuming that in category table you have these fields: id, name, parent_id.

Here is the code:

public static function getHierarchy() {
        $options = [];
        $parents = self::find()->where("parent_id=0")->all();
        foreach($parents as $id => $p) {
            $children = self::find()->where("parent_id=:parent_id", [":parent_id"=>$p->id])->all();
            $child_options = [];
            foreach($children as $child) {
                $child_options[$child->id] = $child->name;
            $options[$p->name] = $child_options;
        return $options;


Now we can proceed to form, and put there something like this.

Html::dropDownList('Post[category]', $model->category, app\models\Category::getHierarchy(), ['prompt' => 'Category'] );

or alternatively.

                $form->field($model, 'category', [
                    'inputOptions' => [
                        'class' => 'selectpicker '
                )->dropDownList(app\models\Category::getHierarchy(), ['prompt' => 'Category', 'class'=>'form-control required']);



About the Author

Edgar Marukyan is an expert of website development and performance optimization, who maintains and consults clients with high load traffic websites.. If you need an assistance, feel free to drop me a line.         Website - Twitter - Facebook

Comments (3)

Trackback URL | Comments RSS Feed

  1. Evgeny says:

    Great! Thanks!

  2. jaszczomp says:

    What about use ArrayHelper::map

    $children = self::find()->where(“parent_id=:parent_id”, [“:parent_id”=>$p->id])->asArray()->all();
    $options[$p->name] = ArrayHelper::map($children, ‘id’, ‘name);


  3. molana says:

    thanks Marukyan..

Leave a Reply to jaszczomp

If you want a picture to show with your comment, go get a Gravatar.

Warning: Use of undefined constant XML - assumed 'XML' (this will throw an Error in a future version of PHP) in /homepages/26/d285632327/htdocs/ on line 1048