duankuaiwang2706 2019-01-21 10:58
浏览 171
已采纳

Yii2使用数据库创建动态导航

I'm implementing a dynamic navbar in Yii2 which displays a dropdown menu picking items from the database. Now, the problem is that when I call the function in which I fill the array, the system crash with the error:

"Invalid argument supplied for foreach()"

since it doesn't find the variable with the array of items. I don't know which controller should pass the arguments to the main view, I just need an array of all items in a data model (i.e. Course).

I've tried out with this but still doesn't work.

  /* @var $courses \app\models\Course[] */

layouts/main

function items($courses)
{
    $items = [];
    foreach ($courses as $course) {
        array_push($items, ['label' => $course->title, 'url' => 
        Url::to(['course', 'id' => $course->id])]);
    }
    return $items;
}

$menuItems = [
// other items ...
    'label' => 'Courses', 'items' => items($courses)
];

echo Nav::widget([
    'options' => ['class' => 'uk-navbar-item'],
    'encodeLabels' => false,
    'items' => $menuItems
 ]);

How can I pass the $courses variable to the layouts/main view? Thanks everyone in advance.

  • 写回答

1条回答 默认 最新

  • douchendan0040 2019-01-21 14:47
    关注

    You should extract this code into widget:

    class MainMenu extends Widget {
    
        public function run() {
            echo Nav::widget([
                'options' => ['class' => 'uk-navbar-item'],
                'encodeLabels' => false,
                'items' => $this->getItems(),
            ]);
        }
    
        protected function getItems() {
            return [
                // other items ...
                ['label' => 'Courses', 'items' => $this->getCoursesItems()],
            ];
        }
    
        protected function getCoursesItems() {
            $items = [];
            foreach (Course::find()->all() as $course) {
                $items[] = [
                    'label' => $course->title,
                    'url' => Url::to(['/course', 'id' => $course->id]),
                ];
            }
            return $items;
        }
    }
    

    Then in your layout you're just calling:

    <?= MainMenu::widget() ?>
    

    In this way you can keep your controller and view clean.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 在若依框架下实现人脸识别
  • ¥15 网络科学导论,网络控制
  • ¥100 安卓tv程序连接SQLSERVER2008问题
  • ¥15 利用Sentinel-2和Landsat8做一个水库的长时序NDVI的对比,为什么Snetinel-2计算的结果最小值特别小,而Lansat8就很平均
  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同