Reputation:
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?
Upvotes: 0
Views: 726
Reputation: 616
you can do small trick :-)
open the tag in the labelTemplet and close it in the submenuTemplate
echo Menu::widget([
'encodeLabels' => true,
'activateParents' => true,
'labelTemplate'=>"<li class=''>
<a href='javascript:;' class='has-arrow' aria-expanded='false'>
<div class='parent-icon'>
<ion-icon name='home-sharp' role='img' class='md hydrated' aria-label='home sharp'></ion-icon>
</div>
<div class='menu-title'>{label}</div>
</a>
",
'submenuTemplate' => " <ul class='mm-collapse' style='height: 0px;'>{items}</ul>
</li>
",
'items' => require '_menu_items.php',
]);
as you can see i started the <li>
in labelTemplate and close it in the submenuTemplate it workes for me
Upvotes: 0
Reputation: 3008
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
],
]
]);
Upvotes: 0
Reputation: 133360
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
],
],
Upvotes: 1