/application/admin/validate/Category.php 代码
<?php
namespace app\admin\validate;
use think\Validate;
class Category extends Validate{
protected $rule = [
['name','require|max:10','分类不能为空!|分类名不能超过10!'],
['parent_id','number'],
['id','number'],
['status','number|in:-1,0,1','状态必须为数字|状态范围不合法!'],
['listorder','number'],
];
/*验证场景设置*/
protected $sence = [
'add' => ['name','parent_id','id'],
'listorder' => ['id', 'listorder'],
'status' => ['id', 'status'],
];
}
?>
/application/admin/controller/Category.php 代码
<?php
namespace app\admin\controller;
use think\Controller;
class Category extends Controller
{
private $obj;
public function _initialize(){
$this->obj = model('Category');
}
public function index()
{
$parentId = input('get.parent_id',0,'intval');
$categorys = $this->obj->getFirstCategory($parentId);
$this->assign('categorys', $categorys);
return $this->fetch();
}
public function add()
{
$categorys = $this->obj->getNormalFirstCategory();
return $this->fetch('',['categorys' => $categorys]);
}
public function save()
{
if(!request()->isPost()){
$this->error('请求失败');
}
$data = input('post.');
$validate = validate('Category');
if(!$validate->scene('add')->check($data)){
$this->error($validate->getError());
}
if(!empty($data['id'])){
return $this->update($data);
}
//把$data数据提交给model层
$res = $this->obj->add($data);
if($res){
$this->success('新增成功!');
}else{
$this->error('新增失败!');
}
}
public function edit($id = 0){
if(intval($id)<1){
$this->error('参数不合法');
}
$category = $this->obj->get($id);
$categorys = $this->obj->getNormalFirstCategory();
$this->assign('category', $category);
$this->assign('categorys', $categorys);
return $this->fetch();
}
public function update($data){
$res = $this->obj->save($data,['id' => intval($data['id'])]);
if($res){
$this->success('更新成功');
}else{
$this->error('更新失败');
}
}
public function listorder($id,$listorder){
$res = $this->obj->save(['listorder'=>$listorder],['id'=>$id]);
if($res){
$this->result($_SERVER['HTTP_REFERER'],1,'更新成功');
}else{
$this->result($_SERVER['HTTP_REFERER'],0,'更新成功');
}
}
public function status(){
$data = input('get.');
$validate = Validate('Category');
$validate->scene('status')->check($data);
if(!$validate->scene('status')->check($data)){
$this->error($validate->getError());
}
$res = $this->obj->save(['status'=>$data['status']],['id'=>$data['id']]);
if($res){
$this->success('更新成功');
}else{
$this->error('更新失败');
}
}
}
?>
删除和修改状态时总是提醒:分类不能为空!