On this page
编辑用户
控制器:app/controller/admin/user.js
js
async edit(){
const { ctx, app } = this;
const id = ctx.params.id
let data = await app.model.User.findOne({
where:{
id
}
})
if(!data){
return await ctx.pageFail('该记录不存在')
}
data = JSON.parse(JSON.stringify(data))
delete data.password
await ctx.renderTemplate({
id:ctx.params.id,
title: "修改用户",
tempType: "form",
form: {
// 提交地址
action: "/admin/user/" + ctx.params.id,
fields:[{
label: "用户名",
type: "text",
name: "username",
placeholder: "用户名",
}, {
label: "密码",
type: "text",
name: "password",
placeholder: "密码"
}, {
label: "头像",
type: "file",
name: "avatar",
}, {
label: "金币",
type: "number",
name: "coin",
default: 0
}],
data
},
// 新增成功跳转路径
successUrl:"/admin/user"
})
}
async update(){
const { ctx, app } = this;
ctx.validate({
id:{
type:"int",
required:true
},
username:{
type:"string",
required:true
},
password:{
type:"string",
},
avatar:{
type:"string",
},
coin:{
type:"int",
}
})
const id = ctx.params.id
const { username,password,avatar,coin } = ctx.request.body
// 用户名是否被使用
const Op = app.Sequelize.Op;
if(await app.model.User.findOne({
where:{
id:{
[Op.ne]: id,
},
username
}
})){
return ctx.apiFail('该用户名已存在')
}
// 当前管理员是否存在
let user = await app.model.User.findOne({
where:{
id
}
})
if(!user){
return ctx.apiFail('该记录不存在')
}
user.username = username
user.avatar = avatar
user.coin = coin
if(password){
user.password = password
}
ctx.apiSuccess(await user.save())
}
路由:app/router.js
js
router.get("/admin/user/edit/:id", controller.admin.user.edit);
router.post("/admin/user/:id", controller.admin.user.update);