如何从数据库中获取数据并在yii2中设置为子菜单? [英] How to fetch data from database and set as submenus in yii2?

查看:38
本文介绍了如何从数据库中获取数据并在yii2中设置为子菜单?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在yii2中有一个小部件菜单:

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
                    ],
               }
           ],

此代码不正确.我应该使用foreach循环吗?或者此小部件有这种可能性?您是否有示例代码?

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?

推荐答案

以这种方式:

// 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
    ];
}
?>

然后打印输出

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 
            ],
        ]
]);

这篇关于如何从数据库中获取数据并在yii2中设置为子菜单?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆