Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save condor-bird/cf19e3dd170bbb5d48aa8c58b2c0529e to your computer and use it in GitHub Desktop.
Save condor-bird/cf19e3dd170bbb5d48aa8c58b2c0529e to your computer and use it in GitHub Desktop.
Yii2 dropdown select optgroup
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;
}
<?=
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