Add models to a RainLab.Sitemap or RainLab.Pages menu
11
To add all entries of a specific model to a RainLab.Sitemap
or RainLab.Pages
menu do the following:
In your Plugin.php
add the following three event listeners. Replace the your-items
key with a more descriptive string.
public function boot()
{
\Event::listen('pages.menuitem.listTypes', function () {
return [
'your-items' => 'Name of the items',
];
});
\Event::listen('pages.menuitem.getTypeInfo', function ($type) {
if ($type === 'your-items') {
$theme = \Cms\Classes\Theme::getActiveTheme();
$pages = \Cms\Classes\Page::listInTheme($theme, true);
return [
'dynamicItems' => true,
'cmsPages' => $pages,
];
}
});
\Event::listen('pages.menuitem.resolveItem', function ($type, $item, $url, $theme) {
if ($type === 'your-items') {
return YourModel::resolveMenuItem($item, $url, $theme);
}
});
}
Then add the resolveMenuItem
method to your Model. The method has to return an array of all the items you want to add. The example code below fetches all models from the database and generates the link using a specific cms page.
public static function resolveMenuItem($item, $url, $theme)
{
$pageName = $item->cmsPage;
$cmsPage = \Cms\Classes\Page::loadCached($theme, $pageName);
$items = self
::orderBy('created_at', 'DESC')
->get()
->map(function (self $item) use ($cmsPage, $url, $pageName) {
$pageUrl = $cmsPage->url($pageName, ['slug' => $item->slug]);
return [
'title' => $item->name,
'url' => $pageUrl,
'mtime' => $item->updated_at,
'isActive' => $pageUrl === $url,
];
})
->toArray();
return [
'items' => $items,
];
}
You will now find your new menu items type in the respective editors of RainLab.Sitemap
and RainLab.Pages
.
Great, how to do the same when creating a link from the rich editor ? Thanks