['name','sort','icon','pid'], self::SCENARIO_EDIT => ['id','name','sort','icon','pid'], ]; } public function attributeLabels() { return [ 'id' => 'ID', 'name' => '名称', 'icon' => '图标', 'sort' => '排序', 'pid' => '父级分类ID' ]; } public function rules() { return [ [['name'], 'required', 'on' => self::SCENARIO_ADD], [['id','name','sort'], 'required', 'on' => self::SCENARIO_EDIT], ['sort', 'default', 'value' => 1], ['sort', 'integer'], ['icon', 'default', 'value' => 0], ['pid', 'default', 'value' => 0], ['name', 'checkName'], ['pid','checkPid','on' => self::SCENARIO_EDIT], ]; } public function checkName($attribute, $params) { $res = CoinApplicationCategory::find()->where(['name' => $this->$attribute])->one(); $scenario = $this->getScenario(); if($scenario == self::SCENARIO_ADD){ if($res){ $this->addError($attribute,'应用分类名称已存在'); } }else if($scenario == self::SCENARIO_EDIT){ if($res && $res->id != $this->id){ $this->addError($attribute,'应用分类名称已存在'); } } } public function checkPid($attribute, $params) { if($this->pid == $this->id){ $this->addError($attribute,'不能设置为自己的子分类'); } } /** * 添加应用分类 */ public function add() { if($this->validate()){ $coin_applicate_category = new CoinApplicationCategory(); $coin_applicate_category->setAttributes($this->attributes,false); $coin_applicate_category->save(); $items = CoinApplicationCategory::getItemsByPid(0); return ['code' => 0,'msg' => '应用分类添加成功!']; }else{ $error = self::getModelError($this); return ['code' => 1,'msg' => $error]; } } /** * 编辑应用分类 */ public function edit() { if($this->validate()){ $coin_applicate_category = CoinApplicationCategory::getCategoryById($this->id); if($coin_applicate_category){ $coin_applicate_category->setAttributes($this->attributes,false); $coin_applicate_category->save(); return ['code' => 0,'msg' => '应用分类修改成功!']; }else{ return ['code' => 1,'msg' => '应用分类不存在']; } }else{ $error = self::getModelError($this); return ['code' => 1,'msg' => $error]; } } /** * @param $id * 删除应用分类 */ public function del($id) { $coin_applicate_category = CoinApplicationCategory::getCategoryById($id); if($coin_applicate_category){ $hasChild = CoinApplicationCategory::hasChildCategory($id); if($hasChild){ return ['code' => 1,'msg' => '应用分类存在子分类,不能删除']; } $coin_applicate_category->delete(); $items = CoinApplicationCategory::getItemsByPid(0); return ['code' => 0,'msg' => '应用分类删除成功']; }else{ return ['code' => 1,'msg' => '应用分类不存在']; } } }