Monday, November 7, 2022

[FIXED] How to fetch data from database and set as submenus in yii2?

Issue

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?


Solution

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


Answered By - Fabrizio Caldarelli
Answer Checked By - Candace Johnson (PHPFixing Volunteer)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.