如何从数据库中获取数据并在yii2中设置为子菜单?

时间:2016-08-18 18:36:53

标签: database loops menu yii2 widget

我在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
                    ],
                    ...
                ],
            ],

]);

我想从数据库中获取子菜单项。这意味着项目数可能会有所不同。我无法手动输入项目。如:

'items' => [
                    $query="select title from book";
                    foreach($query as $items){

                    ['label' => $items['title'],
                        'url' => ['users/..'],
                        'visible' => !Yii::$app->user->isGuest
                    ],
               }
           ],

此代码不正确。 我应该使用foreach循环吗?或者这个小部件有这种可能吗?你有代码示例吗?

2 个答案:

答案 0 :(得分:1)

您可以在窗口小部件外部构建子菜单并为其分配

              $models=YouBookModel::find()->select( 'title')->findAll();
              $subMenu = '';
              foreach($models as $items){

                 $subMenu .= "['label' => $items['title'],
                      'url' => ['users/..'],
                      'visible' => !Yii::$app->user->isGuest
                  ],";
              }

然后

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

答案 1 :(得分:0)

这样:

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