其他分享
首页 > 其他分享> > Yii2与layuiadmin整合2

Yii2与layuiadmin整合2

作者:互联网

17.建立模板文件 /modules/users/views/user/create.php
添加以下内容

<?php
use yii\widgets\ActiveForm;
?>
<div class="layui-form" lay-filter="layuiadmin-form-admin" id="layuiadmin-form-admin">
    <?php $form = ActiveForm::begin();?>
    <div class="layui-form-item">
        <?= $form->field($model, 'username')
            ->textInput(['type' => 'text', 'lay-verify' => 'required','class' => 'layui-input','placeholder' => '用户名'])
            ->label('用户名');
        ?>
    </div>
    <div class="layui-form-item">
        <?= $form->field($model, 'password')
            ->textInput(['type' => 'password','id' => 'LAY-user-login-password', 'lay-verify' => 'required','class' => 'layui-input','placeholder' => '密码'])
            ->label('密码');
        ?>
    </div>

    <div class="layui-form-item">
        <button class="layui-btn layui-btn-fluid" lay-submit lay-filter="LAY-user-login-submit">注册</button>
    </div>

    <?php ActiveForm::end();?>
</div>

此时访问  http://yii2web.com/users/user/create 添加对应的用户信息

18.修改 /controllers/SiteController.php中的方法

  // 
    public function actionLogin()
    {
        $this->layout='empty';
        if (!Yii::$app->user->isGuest) {
            return $this->goHome();
        }

        $model = new LoginForm();
        if ($model->load(Yii::$app->request->post()) && $model->login()) {
            return $this->goBack();
        }

        $model->password = '';

        return $this->render('login', [
            'model' => $model,
        ]);


    }

19.修改公共模板  /views/layouts/main.php

<?php
use yii\helpers\Html;
use \yii\helpers\Url;
use app\assets\LayuiAsset;

LayuiAsset::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, maximum-scale=1">
    <?= Html::csrfMetaTags() ?>
    <title><?= Html::encode($this->title) ?></title>
    <?php $this->head() ?>
</head>
<body class="layui-layout-body">
<?php $this->beginBody() ?>
<div id="LAY_app">
    <div class="layui-layout layui-layout-admin">
        <div class="layui-header">
            <!-- 头部区域 -->
            <ul class="layui-nav layui-layout-left">
                <li class="layui-nav-item layadmin-flexible" lay-unselect>
                    <a href="javascript:;" layadmin-event="flexible" title="侧边伸缩">
                        <i class="layui-icon layui-icon-shrink-right" id="LAY_app_flexible"></i>
                    </a>
                </li>
            </ul>
            <ul class="layui-nav layui-layout-right" lay-filter="layadmin-layout-right">
                <li class="layui-nav-item" lay-unselect>
                    <a href="javascript:;">
                        <cite>贤心</cite>
                    </a>
                    <dl class="layui-nav-child">
                        <dd><a lay-href="set/user/info.html">基本资料</a></dd>
                        <dd><a lay-href="set/user/password.html">修改密码</a></dd>
                        <hr>

                    <?php echo Html::beginForm(['/site/logout'], 'post', ['class' => 'form-inline']);
                    echo Html::submitButton(
                    '退出 (' . Yii::$app->user->identity->username . ')');
                    echo Html::endForm();
                    ?>
                    </dl>
                </li>


            </ul>
        </div>

        <!-- 侧边菜单 -->
        <div class="layui-side layui-side-menu">
            <div class="layui-side-scroll">
                <div class="layui-logo" lay-href="home/console.html">
                    <span>layuiAdmin</span>
                </div>

                <ul class="layui-nav layui-nav-tree" lay-shrink="all" id="LAY-system-side-menu" lay-filter="layadmin-system-side-menu">
                    <li data-name="home" class="layui-nav-item layui-nav-itemed">
                        <a href="javascript:;" lay-tips="主页" lay-direction="2">
                            <i class="layui-icon layui-icon-home"></i>
                            <cite>主页</cite>
                        </a>
                        <dl class="layui-nav-child">
                            <dd data-name="console" class="layui-this">
                                <a lay-href="home/console.html">控制台</a>
                            </dd>
                            <dd data-name="console">
                                <a lay-href="home/homepage1.html">主页一</a>
                            </dd>


                        </dl>
                    </li>


                </ul>
            </div>
        </div>




        <!-- 主体内容 -->
        <div class="layui-body" id="LAY_app_body">
            <div class="layadmin-tabsbody-item layui-show">
                <?= $content ?>
            </div>
        </div>

        <!-- 辅助元素,一般用于移动设备下遮罩 -->
        <div class="layadmin-body-shade" layadmin-event="shade"></div>
    </div>
</div>


<?php $this->endBody() ?>
<script>
    layui.config({
        base: '/assets/layuiadmin/' //静态资源所在路径
    }).extend({
        index: 'lib/index' //主入口模块
    }).use(['index']);
</script>
</body>
</html>
<?php $this->endPage() ?>

此时登陆成功后,显示出整个页面了
接下来,加用户登陆认证添加上去

20.运行 http://yii2web.com/gii/controller
生成

// Controller Class
app\controllers\BaseController

21. 修改文件 /controllers/BaseController.php

<?php

namespace app\controllers;

use Yii;
use yii\web\Controller;

class BaseController extends Controller
{
    public $layout = '@app/views/layouts/main';
    public $topMenu = [];
    public $leftMenu = [];
    // 无用权限控制的路由
    public $routeWhiteList = [
      'site/login',
      'site/error',
      'site/logout'
    ];

    public function beforeAction($action)
    {
        if(Yii::$app->user->isGuest && !in_array($this->route,$this->routeWhiteList)) {
            $this->redirect(['site/login']);
        }
        return parent::beforeAction($action);
    }
}

22. 修改 /controllers/SiteController.php
让其继承上面的 BaseController

// class SiteController extends Controller
// 修改为
class SiteController extends BaseController 
{
    // 
}

此时就必须先登陆才能操作了

23.头部导航,开发头部导航,新建文件 /config/menu.php
添加以下内容

<?php
return [
        'menu' => [
            ['label' => '主页',
                'id' => 'basic',
                'items' => [
                    ['label' => '主页概览','items' => [
                       ['label' => '主页展示','url' => '/site'],
                    ]],
                ],
            ],

            ['label' => '订单管理',
                'id' => 'orders',
                'items' => [
                    ['label' => '所有订单','items' => [
                        ['label' => '所有订单列表','url' => '/orders'],
                        ['label' => '所有退货订单列表','url' => '/all_url'],
                        ['label' => '所有作废订单列表','url' => '/all_url'],
                        ['label' => '所有完成订单列表','url' => '/all_url'],
                    ]],
                    ['label' => '亚马逊订单','items' => [
                        ['label' => '亚马逊订单列表','url' => '/url1'],
                        ['label' => '亚马逊退货订单列表','url' => '/url1'],
                        ['label' => '亚马逊作废订单列表','url' => '/url1'],
                        ['label' => '亚马逊完成订单列表','url' => '/url1'],
                    ]],
                    ['label' => '沃尔玛订单','items' => [
                        ['label' => '沃尔玛订单列表','url' => '/url1'],
                        ['label' => '沃尔玛退货订单列表','url' => '/url1'],
                        ['label' => '沃尔玛作废订单列表','url' => '/url1'],
                        ['label' => '沃尔玛完成订单列表','url' => '/url1'],
                    ]],
                ]],

            ['label' => '系统管理',
                'id' => 'system',
                'items' => [
                    ['label' => '权限管理','items' => [
                        ['label' => '角色管理','url' => '/system/role'],
                        ['label' => '权限列表','url' => '/system/permission'],
                        ['label' => '用户权限管理','url' => '/system/userPermission'],
                    ]],

                ]],
            ['label' => '用户管理',
                'id' => 'users',
                'items' => [
                    ['label' => '用户管理','items' => [
                        ['label' => '用户列表','url' => '/users/user'],
                    ]],

                ]],

        ],
    ];

24.继续完善上面的控制器模板
修改文件 /controllers/BaseController.php

    public function beforeAction($action)
    {
        if(Yii::$app->user->isGuest && !in_array($this->route,$this->routeWhiteList)) {
            $this->redirect(['/site/login']);
        }
        $menuFilePath = Yii::getAlias('@app/config/menu.php');
        $menuConfig = require_once $menuFilePath;
        $menus = $menuConfig['menu'];
        $this->topMenu = $menus;
        foreach ($menus as $row_menu) {
            $this->leftMenu[$row_menu['id']] = $row_menu['items'];
        }
        return parent::beforeAction($action);
    }

25. 修改模板  /views/layouts/main.php,为了方便处理,精简一些内容

<?php
use yii\helpers\Html;
use \yii\helpers\Url;
use app\assets\LayuiAsset;

LayuiAsset::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, maximum-scale=1">
    <?= Html::csrfMetaTags() ?>
    <title><?= Html::encode($this->title) ?></title>
    <?php $this->head() ?>
</head>
<body class="layui-layout-body">
<?php $this->beginBody() ?>
<div id="LAY_app">
    <div class="layui-layout layui-layout-admin">
        <div class="layui-header">

            <!-- 头部区域 -->
            <ul class="layui-nav layui-layout-left">
                <li class="layui-nav-item layadmin-flexible" lay-unselect>
                    <a href="javascript:;" layadmin-event="flexible" title="侧边伸缩">
                        <i class="layui-icon layui-icon-shrink-right" id="LAY_app_flexible"></i>
                    </a>
                </li>
                <?php
                foreach ($this->context->topMenu as $item):
                    $menuUrl = $item['items'][0]['items'][0]['url'];
                    $layui_this = '';
                    if($this->context->module->id == $item['id']) {
                        $layui_this = 'layui-this';
                    }
                    ?>
                    <li class="layui-nav-item layui-hide-xs <?= $layui_this;?>" lay-unselect>
                        <?= Html::a($item['label'],$menuUrl,[
                            'data' => [
                                'method' => 'post'
                            ]
                        ])?>
                    </li>
                <?php endforeach;?>

            </ul>
            <ul class="layui-nav layui-layout-right" lay-filter="layadmin-layout-right">
                <li class="layui-nav-item">
                <?php echo Html::beginForm(['/site/logout'], 'post', ['class' => 'form-inline']);
                echo Html::submitButton(
                    '退出 (' . Yii::$app->user->identity->username . ')');
                echo Html::endForm();
                ?>
                </li>

            </ul>
        </div>

        <!-- 侧边菜单 -->
        <div class="layui-side layui-side-menu">
            <div class="layui-side-scroll">
                <div class="layui-logo" lay-href="home/console.html">
                    <span>layuiAdmin</span>
                </div>
                <?php
                    $leftMenuList = $this->context->leftMenu[$this->context->module->id];
                ?>
                <ul class="layui-nav layui-nav-tree" lay-shrink="all" id="LAY-system-side-menu" lay-filter="layadmin-system-side-menu">
                    <?php foreach ($leftMenuList as $row_menu): ?>
                    <li data-name="home" class="layui-nav-item layui-nav-itemed">
                        <a href="javascript:;" lay-tips="<?= $row_menu['label'];?>" lay-direction="2">
                            <i class="layui-icon layui-icon-home"></i>
                            <cite><?= $row_menu['label'];?></cite>
                        </a>
                        <dl class="layui-nav-child">
                            <?php foreach ($row_menu['items'] as $child_menu): ?>
                            <dd>
                                <a href="<?= $child_menu['url'];?>"><?= $child_menu['label'];?></a>
                            </dd>
                            <?php endforeach;?>

                        </dl>
                    </li>
                    <?php endforeach;?>
                </ul>
            </div>
        </div>

        <!-- 主体内容 -->
        <div class="layui-body" id="LAY_app_body">
            <div class="layadmin-tabsbody-item layui-show">
                <?= $content ?>
            </div>
        </div>

        <!-- 辅助元素,一般用于移动设备下遮罩 -->
        <div class="layadmin-body-shade" layadmin-event="shade"></div>
    </div>
</div>


<?php $this->endBody() ?>
<script>
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
</script>
</body>
</html>
<?php $this->endPage() ?>

26.修改各个模板,统一继承 BaseController
比如订单模模块 /modules/orders/controllers/DefaultController.php

class DefaultController extends Controller
// 修改为
class DefaultController extends BaseController

27. 以下开发用户功能,建立文件 /modules/users/views/user/index.php

<div class="layui-fluid">
    <div class="layui-card">

        <div class="layui-card-header layuiadmin-card-header-auto">
            <div class="layui-btn-group">
                <button class="layui-btn layui-btn-sm layui-btn-danger" id="listDelete">删 除</button>
                <a class="layui-btn layui-btn-sm" href="/users/user/create">添 加</a>
                <button class="layui-btn layui-btn-sm" id="memberSearch">搜索</button>
            </div>
            <div class="layui-form">
                <div class="layui-input-inline">
                    <input type="text" name="username" id="username" placeholder="用户名" class="layui-input">
                </div>
                <div class="layui-input-inline">
                    <input type="text" name="email" id="email" placeholder="邮箱" class="layui-input">
                </div>
                <div class="layui-input-inline">
                    <input type="text" name="phone" id="phone" placeholder="手机号码" class="layui-input">
                </div>
            </div>
        </div>

        <div class="layui-card-body">
            <table id="dataTable" lay-filter="dataTable"></table>
            <script type="text/html" id="options">
                <div class="layui-btn-group">
                    <a class="layui-btn layui-btn-sm" lay-event="edit">编辑</a>
                    <a class="layui-btn layui-btn-sm" lay-event="role">角色</a>
                    <a class="layui-btn layui-btn-sm" lay-event="permission">权限</a>
                    <a class="layui-btn layui-btn-danger layui-btn-sm " lay-event="del">删除</a>
                </div>
            </script>
        </div>

    </div>
</div>


<script>


    layui.use(['layer','table','form'],function () {
        var layer = layui.layer;
        var form = layui.form;
        var table = layui.table;

        //用户表格初始化
        var dataTable = table.render({
            elem: '#dataTable'
            ,height: 500
            ,url: "/users/user/user-data" //数据接口
            ,method: 'POST'
            ,page: true //开启分页
            ,cols: [[ //表头
                {checkbox: true,fixed: true}
                ,{field: 'id', title: 'ID', sort: true,width:80}
                ,{field: 'username', title: '用户名'}
                ,{field: 'email', title: '邮箱'}
                ,{field: 'phone', title: '手机号码'}
                ,{field: 'created_at', title: '创建时间', templet : '<div>{{layui.util.toDateString(d.created_at * 1000, "yyyy-MM-dd HH:mm:ss")}}</div>}}'}
                ,{field: 'updated_at', title: '更新时间', templet : '<div>{{layui.util.toDateString(d.updated_at * 1000, "yyyy-MM-dd HH:mm:ss")}}</div>}}'}
                ,{fixed: 'right', width: 320, align:'center', toolbar: '#options'}
            ]]
        });




        //监听工具条
        table.on('tool(dataTable)', function(obj){ //注:tool是工具条事件名,dataTable是table原始容器的属性 lay-filter="对应的值"
            var data = obj.data //获得当前行数据
                ,layEvent = obj.event; //获得 lay-event 对应的值
            if(layEvent === 'del'){
                layer.confirm('确认删除吗?', function(index){
                    $.post("/users/user/delete",{_method:'delete',ids:[data.id]},function (result) {
                        if (result.code==0){
                            obj.del(); //删除对应行(tr)的DOM结构
                        }
                        layer.close(index);
                        layer.msg(result.msg,{icon:6})
                    });
                });
            } else if(layEvent === 'edit'){
                location.href = '/users/user/update?id='+data.id;
            } else if (layEvent === 'role'){

            } else if (layEvent === 'permission'){

            }
        });

        //按钮批量删除
        $("#listDelete").click(function () {
            var ids = []
            var hasCheck = table.checkStatus('dataTable')
            var hasCheckData = hasCheck.data
            if (hasCheckData.length>0){
                $.each(hasCheckData,function (index,element) {
                    ids.push(element.id)
                })
            }
            if (ids.length>0){
                layer.confirm('确认删除吗?', function(index){
                    $.post("/users/user/delete",{_method:'delete',ids:ids},function (result) {
                        if (result.code==0){
                            dataTable.reload()
                        }
                        layer.close(index);
                        layer.msg(result.msg,{icon:6})
                    });
                })
            }else {
                layer.msg('请选择删除项',{icon:5})
            }
        })

        // 搜索
        $("#memberSearch").click(function () {
            var username = $("#username").val();
            var email = $("#email").val();
            var phone = $("#phone").val();
            dataTable.reload({
                where:{username:username,email:email,phone:phone},
                page:{curr:1}
            })
        })
    })




</script>

 

标签:layuiadmin,url,items,label,user,整合,layui,Yii2,id
来源: https://www.cnblogs.com/lin3615/p/15870111.html