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.