layUI下角色与用户绑定 读取数据库 复选框回显

这篇博客展示了如何实现前端用户信息的新增与修改,包括HTML表单设计、数据回显及用户状态、角色选择等功能。后端使用了Java实现更新接口,处理用户角色关系的修改,并通过Ajax进行数据交互。代码示例详细,适合理解前后端交互逻辑。
摘要由CSDN通过智能技术生成

前端代码:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"/>
    <title>新增修改用户详情 - 后台管理系统</title>
    <link href="${ctxPath}/common/bootstrap-v3.3.7/css/bootstrap.min.css" rel="stylesheet">
    <link href="${ctxPath}/common/layui-v2.6.4/css/layui.css">
    <link href="${ctxPath}/css/base/style.min.css" rel="stylesheet">
</head>
<body>
<div class="container-fluid p-t-15">
    <div class="row">
        <div class="col-lg-12">
            <div class="card">
                <div class="card-body">
                    <form class="form-horizontal" method="post" action="#!" onsubmit="return false">
                        <div class="form-group">
                            <div class="col-sm-1 control-label">用户编号</div>
                            <div class="col-sm-2">
                                <input class="form-control" type="userCode" name="userCode" id="userCode"
                                       placeholder="用户编号"/>
                            </div>
                            <div class="col-sm-1 control-label">用户名</div>
                            <div class="col-sm-2">
                                <input class="form-control" type="userName" name="userName" id="userName"
                                       placeholder="用户名"/>
                            </div>
                            <div class="col-sm-1 control-label">登录账户</div>
                            <div class="col-sm-2">
                                <input class="form-control" type="loginName" name="loginName" id="loginName"
                                       placeholder="登录账户"/>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-1 control-label">状态</div>
                            <div class="col-sm-2">
                                <label class="radio-inline">
                                    <input type="radio" name="state" id="state1" value="1"> 启用
                                </label>
                                <label class="radio-inline">
                                    <input type="radio" name="state" id="state2" value="0"> 停用
                                </label>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-1 control-label">角色</div>
                            <div class="col-sm-11 " name="roleName" id="roleName">

                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-1 control-label">岗位id</div>
                            <div class="col-sm-2 ">
                                <select class="form-control" name="postId" id="postId">

                                </select>
                            </div>
                            <div class="col-sm-1 control-label">电话号码</div>
                            <div class="col-sm-2">
                                <input class="form-control" type="phone" name="phone" id="phone" placeholder="电话号码"/>
                            </div>
                            <div class="col-sm-1 control-label">电子邮箱</div>
                            <div class="col-sm-2">
                                <input class="form-control" type="email" name="email" id="email" placeholder="电子邮箱"/>
                            </div>
                            <div class="col-sm-1 control-label">组织机构Id</div>
                            <div class="col-sm-2">
                                <input class="form-control" type="orgId" name="orgId" id="orgId"
                                       placeholder="选择所属组织机构id"/>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-1 control-label">备注</div>
                            <div class="col-sm-3">
                                <input class="form-control" type="remarks" name="remarks" id="remarks"
                                       placeholder="备注"/>
                            </div>
                        </div>
                        <div class="form-group">
                            <div class="col-sm-8 col-sm-offset-5">
                                <button id="post_submit" class="btn btn-primary">保存</button>
                                <button id="reload" class="btn btn-primary btn-warning" style="margin-left: 30px">返回
                                </button>
                            </div>
                        </div>

                    </form>
                </div>
            </div>
        </div>
    </div>
</div>
</body>
<script type="text/javascript" src="${ctxPath}/common/jquery/jquery-3.5.1.min.js"></script>
<script type="text/javascript" src="${ctxPath}/common/bootstrap-v3.3.7/js/bootstrap.min.js"></script>
<script type="text/javascript" src="${ctxPath}/js/base/main.min.js"></script>
<script src="${ctxPath}/common/layui-v2.6.4/layui.js" charset="utf-8"></script>

<script type="text/javascript">
    //编辑页面的数据回显
    var id = "${id}"
    if (id != "" && id != undefined) {
        //回显数据
        getInfo(id);
    }
    //返回
    $('#reload').on('click', function () {
        window.location.href = "${ctxPath}/sys/user";
    });

    //输入完用户相关信息,点击保存
    $('#post_submit').on('click', function () {
        userUpdate();
    });

    function userUpdate() {
        var userCode = $('input[name="userCode"]').val();
        var userName = $('input[name="userName"]').val();
        var postId = $('select[name="postId"]').val();
        var state = $('input[name="state"]:checked').val();
        var phone = $('input[name="phone"]').val();
        var email = $('input[name="email"]').val();
        var checkboxValue = "";
        var roleIdList = new Array();
        $("input:checkbox[name='roleIdList']:checked").each(function () {
            if (checkboxValue == 0) {
                checkboxValue = $(this).val();
                return true;
            }
            checkboxValue += ',' + $(this).val();
        });
        if (checkboxValue.length > 0) {
            for (var i = 0; i < checkboxValue.split(",").length; i++) {
                roleIdList[i] = checkboxValue.split(",")[i]
            }
        } else {
            roleIdList = null;
        }
        console.log(roleIdList);
        if (userCode == "" || userName == "" || state == "" ) {
            return;
        }
        var params = {"userCode": userCode, "userName": userName, "postId": postId, "state": state, "phone": phone, "email": email, "roleIdList": roleIdList, "id": id}
        var url = "${ctxPath}/sys/user/update";
        $.ajax({
            url: url,
            type: "POST",
            data: JSON.stringify(params),
            contentType: "application/json",
            success: function (data) {
                layer.msg(data.msg);
                // console.log(params.roleIdList),
                //跳转到列表页
                window.location.href = "${ctxPath}/sys/user";
                return
            }
        });

    };

    //详情页function
    function getInfo(id) {
        $.get("${ctxPath}/sys/user/info/" + id, function (r) {
            if (r.code == 200) {
                //回显数据
                $("#userCode").val(r.data.userCode);
                $("#userName").val(r.data.userName);
                $("#loginName").val(r.data.loginName);
                switch (r.data.state) {
                    case 0:$("#state2").prop('checked', 'false'); break
                    case 1:$("#state1").prop('checked', 'true'); break
                };
                $("#phone").val(r.data.phone);
                $("#email").val(r.data.email);
                $("#orgId").val(r.data.orgId);
                $("#remarks").val(r.data.remarks);
                postNameList(r.data.postId);
                roleNameList(r.data.roleIdList);
                // console.log(r.data.roleIdList);
            } else {
                alert(r.msg);
            }
        });
    };

    //查询所有岗位,并根据用户id显示该用户岗位
    function postNameList(id) {
        $.ajax({
            url: "${ctxPath}/sys/post/postNameList",
            dataType: "json",
            type: "post",
            success: function (data) {
                $.each(data, function (index) {
                    var postId = data[index].id;
                    var postName = data[index].postName;
                    $("#postId").append("<option value='" + postId + "'>" + postName + "</option>");

                });
                $("#postId").each(function () {
                    // this代表的是,对option再进行遍历
                    $(this).children("option").each(function () {
                        // 判断需要对那个选项进行回显
                        if (this.value == id) {
                            // 进行回显
                            $("#postId").val(this.value);
                        }
                    });
                });
            }
        });
    };

    //查询所有角色
    function roleNameList(arr) {
            $.ajax({
                url: "${ctxPath}/sys/role/roleNameList",
                dataType: "json",
                type: "post",
                success: function (data) {
                    // console.log(data);
                    // console.log(arr);
                    $.each(data, function (index) {
                        var roleId = data[index].id;
                        // console.log(roleId);
                        var roleName = data[index].roleName;
                        // console.log(roleName);
                        $("#roleName").append("<label class='checkbox-inline'>" +
                            "<input type='checkbox'  name='roleIdList' value='" + roleId + "'/> " + roleName +
                            "</label>" +
                            "&nbsp;&nbsp;&nbsp;&nbsp;");
                        //每一行设置5个角色,超过5个自动换下一行
                        if ((index + 1) % 5 == 0) {
                            $("#roleName").append("<br>")
                        }
                    });
                    //遍历从数据库中查到的角色id
                    $.each(arr, function (index) {
                        // console.log(arr[index]);
                        //遍历name='roleIdList'的input标签
                        $("input[name='roleIdList']").each(function () {
                            //将遍历到的input标签的value属性值与遍历数组的元素比较,并回显
                            if ($(this).val() == arr[index]) {
                                // console.log($(this).val());
                                // $(this).attr("checked", true);
                                $(this).prop('checked', true);
                            }
                        });
                    });
                },
            });
    };

</script>
</html>

后端代码:

Controller层

    public JsonResult update(@RequestBody SysUserEntity sysUser) {
        PreDaoUtils.preUpdate(sysUser);
        sysUserService.updateByUser(sysUser);
        return JsonResult.success();
    }

Service层

  public boolean updateByUser(SysUserEntity sysUser) {
        //引入项目框架的方法,在更新之前执行的操作
        PreDaoUtils.preUpdate(sysUser);
        
        saveUserRole(sysUser.getId(), sysUser.getRoleIdList());
        System.out.println(sysUser);
        return super.updateTemplate(sysUser);
    }

    /**
     * 修改用户与角色的关系
     *
     * @param
     */
    private void saveUserRole(String userId, List<String> roleIdList) {
        //首先删除用户与角色的关系
        sysUserRoleDao.deleteByUserId(userId);

        System.out.println(userId);
        System.out.println(roleIdList);

        if (CollectionUtils.isEmpty(roleIdList)) {
            return;
        }
        //保存修改后用户与角色的关系
        for (String roleId : roleIdList) {
            SysUserRoleEntity sysUserRole = new SysUserRoleEntity();
            sysUserRole.setUserId(userId);
            sysUserRole.setRoleId(roleId);
            System.out.println(roleId);
            System.out.println(sysUserRole.getRoleId());
            PreDaoUtils.preInsert(sysUserRole);
            sysUserRoleDao.insert(sysUserRole);
        }
    }

页面功能展示:

 不喜勿喷,只留做个人记录,如果恰好能帮助到你们那是最好的!

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值