Меню mdmsoft-yii2-admin

Всё про контроль доступа пользователей: фильтры, RBAC, проверки
Ответить
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Меню mdmsoft-yii2-admin

Сообщение svil »

Смотрела документацию https://github.com/mdmsoft/yii2-admin/b ... ng-menu.md
Вывожу меню в main.php

Код: Выделить всё

<?php

/* @var $this \yii\web\View */
/* @var $content string */

use app\widgets\Alert;
use yii\helpers\Html;
use yii\bootstrap\Nav;
use yii\bootstrap\NavBar;
use yii\widgets\Breadcrumbs;
use app\assets\AppAsset;


use mdm\admin\components\MenuHelper;

AppAsset::register($this);




?>
<?php $this->beginPage() ?>
<!DOCTYPE html>

<html lang="<?= Yii::$app->language ?>">
<head>
    <meta charset="<?= Yii::$app->charset ?>">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <?php $this->registerCsrfMetaTags() ?>
    <title><?= Html::encode($this->title) ?></title>
    <?php $this->head() ?>
</head>
<body>
<?php $this->beginBody() ?>

<div class="wrap">
    <?php
    NavBar::begin([
        'brandLabel' => Yii::$app->name,
        'brandUrl' => Yii::$app->homeUrl,
        'options' => [
            'class' => 'navbar-inverse navbar-fixed-top',
        ],
    ]);
    echo Nav::widget([
        'options' => ['class' => 'navbar-nav navbar-right'],
        'items' => [
            ['label' => 'Главная', 'url' => ['/site/index']],
            ['label' => 'Посты', 'url' => ['/post/index']],
            ['label' => 'About', 'url' => ['/site/about']],
            ['label' => 'Contact', 'url' => ['/site/contact']],
            ['label' => 'Вход в admin', 'url' => ['/admin']],
            ['label' => 'Вход в rbac', 'url' => ['/rbac']],
            ['label' => 'Регистрация', 'url' => ['/site/signup']],
            ['label' => 'rbac/user', 'url' => ['/rbac/user']],
            Yii::$app->user->isGuest ? (
                ['label' => 'Войти', 'url' => ['/site/login']]
            ) : (
                '<li>'
                . Html::beginForm(['/site/logout'], 'post')
                . Html::submitButton(
                    'Выйти (' . Yii::$app->user->identity->username . ')',
                    ['class' => 'btn btn-link logout']
                )
                . Html::endForm()
                . '</li>'
            )
        ],
    ]);
    NavBar::end();
    ?>

    <div class="container">
        <?= Breadcrumbs::widget([
            'links' => isset($this->params['breadcrumbs']) ? $this->params['breadcrumbs'] : [],
        ]) ?>
        <?= Alert::widget() ?>

<?= Nav::widget([

    'items' => MenuHelper::getAssignedMenu(Yii::$app->user->id)]);  // ВОТ ВЫВЕДЕННОЕ МЕНЮ


?>

        <?= $content ?>
    </div>
</div>

<footer class="footer">
    <div class="container">
        <p class="pull-left">&copy; My Company <?= date('Y') ?></p>

        <p class="pull-right"><?= Yii::powered() ?></p>
    </div>
</footer>

<?php $this->endBody() ?>
</body>
</html>
<?php $this->endPage() ?>
Куда вставлять этот код из документации

Код: Выделить всё

Return of mdm\admin\components\MenuHelper::getAssignedMenu() has default format like:

[
    [
        'label' => $menu['name'], 
        'url' => [$menu['route']],
        'items' => [
			[
				'label' => $menu['name'], 
				'url' => [$menu['route']]
            ],
            ....
        ]
    ],
    [
        'label' => $menu['name'], 
        'url' => [$menu['route']],
        'items' => [
			[
				'label' => $menu['name'], 
				'url' => [$menu['route']]
            ]
        ]
    ],
    ....
]
s-sergey1990
Сообщения: 21
Зарегистрирован: 2014.07.01, 23:11

Re: Меню mdmsoft-yii2-admin

Сообщение s-sergey1990 »

это структура которая возвращается MenuHelper::getAssignedMenu(), проверьте через var_dump банально
Аватара пользователя
svil
Сообщения: 563
Зарегистрирован: 2018.02.12, 22:41

Re: Меню mdmsoft-yii2-admin

Сообщение svil »

Значит настраивать надо в админке rbac?
Но там один маршрут можно выбрать. Мне непонятно, откуда структура берется со многими маршрутами.
s-sergey1990
Сообщения: 21
Зарегистрирован: 2014.07.01, 23:11

Re: Меню mdmsoft-yii2-admin

Сообщение s-sergey1990 »

https://mdmsoft.github.io/yii2-admin/md ... elper.html
я никогда не использовал это, но как я понял можно переопределить
https://github.com/mdmsoft/yii2-admin/b ... Helper.php
public static function getAssignedMenu
вот тут ковыряйте код
rosswe
Сообщения: 95
Зарегистрирован: 2017.01.09, 03:27
Откуда: Ставрополь
Контактная информация:

Re: Меню mdmsoft-yii2-admin

Сообщение rosswe »

Откажитесь от mdmsoft/yii2-admin (он касячный) возьмите - dektrium/yii2-rbac
Loveorigami
Сообщения: 977
Зарегистрирован: 2014.08.27, 21:54

Re: Меню mdmsoft-yii2-admin

Сообщение Loveorigami »

У себя я дорабатывал виджет меню

Код: Выделить всё

<?php

namespace lo\core\widgets\admin;

use Yii;
use yii\helpers\ArrayHelper;
use yii\helpers\Html;
use yii\helpers\Url;

/**
 * Class Menu
 * @package lo\core\widgets\admin
 */
class Menu extends \yii\widgets\Menu
{
    /** @var string */
    public $linkTemplate = "<a href=\"{url}\">\n{icon}\n{label}\n{right-icon}\n{badge}</a>";

    /** @var string */
    public $labelTemplate = '{icon}\n{label}';
    public $submenuTemplate = "\n<ul class='treeview-menu' {show}>\n{items}\n</ul>\n";
    public $activateParents = true;
    public $defaultIconHtml = '<i class="fa fa-circle-o"></i> ';

    /** @var string */
    public $parentRightIcon = '<i class="fa fa-angle-left pull-right"></i>';


    /**
     * @inheritdoc
     */
    protected function renderItem2($item)
    {
        if (isset($item['items'])) {
            $labelTemplate = '<a href="{url}">{icon} {label} <span class="pull-right-container"><i class="fa fa-angle-left pull-right"></i></span></a>';
            $linkTemplate = '<a href="{url}">{icon} {label} <span class="pull-right-container"><i class="fa fa-angle-left pull-right"></i></span></a>';
        } else {
            $labelTemplate = $this->labelTemplate;
            $linkTemplate = $this->linkTemplate;
        }

        $replacements = [
            '{label}' => strtr($this->labelTemplate, ['{label}' => $item['label'],]),
            '{icon}' => empty($item['icon']) ? $this->defaultIconHtml
                : '<i class="' . self::$iconClassPrefix . $item['icon'] . '"></i> ',
            '{url}' => isset($item['url']) ? Url::to($item['url']) : 'javascript:void(0);',
        ];

        $template = ArrayHelper::getValue($item, 'template', isset($item['url']) ? $linkTemplate : $labelTemplate);
        return strtr($template, $replacements);
    }

    /**
     * @inheritdoc
     */
    protected function renderItem($item)
    {

        if (isset($item['items']) && !isset($item['right-icon'])) {
            $item['right-icon'] = $this->parentRightIcon;
        }

        if (isset($item['url'])) {
            $template = ArrayHelper::getValue($item, 'template', $this->linkTemplate);

            return strtr($template, [
                '{icon}' => isset($item['icon']) ? $item['icon'] : '',
                '{right-icon}' => isset($item['right-icon']) ? $item['right-icon'] : '',
                '{url}' => Url::to($item['url']),
                '{label}' => $item['label'],
            ]);
        } else {
            $template = ArrayHelper::getValue($item, 'template', $this->labelTemplate);
            return strtr($template, [
                '{icon}' => isset($item['icon']) ? $item['icon'] : '',
                '{right-icon}' => isset($item['right-icon']) ? $item['right-icon'] : '',
                '{label}' => $item['label'],
            ]);
        }
    }

    /**
     * Recursively renders the menu items (without the container tag).
     * @param array $items the menu items to be rendered recursively
     * @return string the rendering result
     */
    protected function renderItems($items)
    {
        $n = count($items);
        $lines = [];
        foreach ($items as $i => $item) {
            $options = array_merge($this->itemOptions, ArrayHelper::getValue($item, 'options', []));
            $tag = ArrayHelper::remove($options, 'tag', 'li');
            $class = [];
            if ($item['active']) {
                $class[] = $this->activeCssClass;
            }
            if ($i === 0 && $this->firstItemCssClass !== null) {
                $class[] = $this->firstItemCssClass;
            }
            if ($i === $n - 1 && $this->lastItemCssClass !== null) {
                $class[] = $this->lastItemCssClass;
            }
            if (!empty($class)) {
                if (empty($options['class'])) {
                    $options['class'] = implode(' ', $class);
                } else {
                    $options['class'] .= ' ' . implode(' ', $class);
                }
            }
            $menu = $this->renderItem($item);
            if (!empty($item['items'])) {
                $menu .= strtr($this->submenuTemplate, [
                    '{show}' => $item['active'] ? "style='display: block'" : '',
                    '{items}' => $this->renderItems($item['items']),
                ]);
                if (isset($options['class'])) {
                    $options['class'] .= ' treeview';
                } else {
                    $options['class'] = 'treeview';
                }
            }
            $lines[] = Html::tag($tag, $menu, $options);
        }
        return implode("\n", $lines);
    }

    /**
     * Checks whether a menu item is active.
     * This is done by checking if [[route]] and [[params]] match that specified in the `url` option of the menu item.
     * When the `url` option of a menu item is specified in terms of an array, its first element is treated
     * as the route for the item and the rest of the elements are the associated parameters.
     * Only when its route and parameters match [[route]] and [[params]], respectively, will a menu item
     * be considered active.
     * @param array $item the menu item to be checked
     * @return boolean whether the menu item is active
     */
    protected function isItemActive($item)
    {
        if (isset($item['url']) && is_array($item['url']) && isset($item['url'][0])) {
            $route = Yii::getAlias($item['url'][0]);

            if (!$route) return false;

            if ($route[0] !== '/' && Yii::$app->controller) {
                $route = Yii::$app->controller->module->getUniqueId() . '/' . $route;
            }

            $this->route = str_replace('/update', '/index', $this->route);
            if (ltrim($route, '/') !== $this->route) {
                return false;
            }
            unset($item['url']['#']);
            if (count($item['url']) > 1) {
                $params = $item['url'];
                unset($params[0]);
                foreach ($params as $name => $value) {
                    if ($value !== null && (!isset($this->params[$name]) || $this->params[$name] != $value)) {
                        return false;
                    }
                }
            }

            return true;
        }

        return false;
    }
}


во вьюшке

Код: Выделить всё


        $callback = function ($menu) {
            // @todo replace for json_decode
            $data = eval($menu['data']);
            $data['icon'] = isset($data['icon']) ? '<i class="fa fa-' . $data['icon'] . '"></i>' : '<i class="fa fa-angle-double-right"></i>';

            return [
                'label' => Yii::t('backend', $menu['name']),
                'url' => [$menu['route']],
                'icon' => $data['icon'],
                'items' => $menu['children'],
            ];
        };
        
            echo Menu::widget([
                'options' => ['class' => 'sidebar-menu', 'data-widget' => 'tree'],
                'labelTemplate' => '<a href="#">{icon}<span>{label}</span>{right-icon}</a>',
                'linkTemplate' => '<a href="{url}">{icon}<span>{label}</span>{right-icon}</a>',
                'submenuTemplate' => "\n<ul class=\"treeview-menu\">\n{items}\n</ul>\n",
                'activateParents' => true,
                'items' => MenuHelper::getAssignedMenu(Yii::$app->user->id, null, $callback),
            ]);
Ответить