Created
April 13, 2018 16:08
-
-
Save condor-bird/cf19e3dd170bbb5d48aa8c58b2c0529e to your computer and use it in GitHub Desktop.
Yii2 dropdown select optgroup
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?= | |
Html::dropDownList('Post[category]', $model->category, app\models\Category::getHierarchy(), ['prompt' => 'Category'] ); | |
?> | |
<?= | |
$form->field($model, 'category', [ | |
'inputOptions' => [ | |
'class' => 'selectpicker ' | |
] | |
] | |
)->dropDownList(app\models\Category::getHierarchy(), ['prompt' => 'Category', 'class'=>'form-control required']); | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment