问题
I have a widget menu in yii2:
<?= \yii\widgets\Menu::widget([
'encodeLabels' => false,
'options' => ['id' => 'dock'],
'items' => [
['label' => 'ab...',
'template' => '<i class="fa fa-dashboard"></i><a href="{url}">{label}</a>',
'options' => ['class' => 'launcher dropdown hover'],
'submenuTemplate' => "\n<ul class='dropdown-menu'>\n{items}\n</ul>\n",
'items' => [
['label' => 'a',
'url' => ['users/..'],
'visible' => Yii::$app->user->isGuest
],
['label' => 'b',
'url' => ['users/..'],
'visible' => Yii::$app->user->isGuest
],
...
],
],
]);
I want to fetch submenu items from database.That's mean the number of items may vary .I can not enter items manually. such as :
'items' => [
$query="select title from book";
foreach($query as $items){
['label' => $items['title'],
'url' => ['users/..'],
'visible' => !Yii::$app->user->isGuest
],
}
],
This code not true. Should I use the foreach loop? OR There is such a possibility for this widget? Do you hava a sample code?
回答1:
In this way:
// If you don't need object representation, you can use an array to speed up the action (and preserve memory)
$models = Model::find()->asArray()->all();
$items = [];
foreach ($models as $m) {
$items[] = [
'label' => $m['title'],
'url' => ['users/..'],
'visible' => !Yii::$app -> user -> isGuest
];
}
?>
and then print the output
echo \yii\widgets\Menu::widget([
'encodeLabels' => false,
'options' => ['id' => 'dock'],
'items' => [
['label' => 'ab...',
'template' => '<i class="fa fa-dashboard"></i><a href="{url}">{label}</a>',
'options' => ['class' => 'launcher dropdown hover'],
'submenuTemplate' => "\n<ul class='dropdown-menu'>\n{items}\n</ul>\n",
'items' => $items
],
]
]);
回答2:
You can build you submenu outside the widget and the assign to it
$models=YouBookModel::find()->select( 'title')->findAll();
$subMenu = '';
foreach($models as $items){
$subMenu .= "['label' => $items['title'],
'url' => ['users/..'],
'visible' => !Yii::$app->user->isGuest
],";
}
then
'items' => [
['label' => 'ab...',
'template' => '<i class="fa fa-dashboard"></i><a href="{url}">{label}</a>',
'options' => ['class' => 'launcher dropdown hover'],
'submenuTemplate' => "\n<ul class='dropdown-menu'>\n{items}\n</ul>\n",
'items' => $subMenu
],
],
来源:https://stackoverflow.com/questions/39025292/how-to-fetch-data-from-database-and-set-as-submenus-in-yii2