| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101 |
- <?php
- namespace common\models\forms;
- use common\helpers\Date;
- use common\components\Model;
- use common\helpers\Form;
- use common\models\ArticleCategory;
- use yii\base\Exception;
- /**
- * Login form
- */
- class ArticleCategoryForm extends Model
- {
- public $id;
- public $cateName;
- public $sort;
- /**
- * @inheritdoc
- */
- public function rules()
- {
- return [
- [['id', 'cateName', 'sort'], 'trim'],
- [['id', 'cateName', 'sort'], 'required'],
- [['id'], 'exist', 'targetClass'=>ArticleCategory::class, 'targetAttribute'=>'ID'],
- [['cateName'], 'unique', 'targetClass'=>ArticleCategory::class, 'targetAttribute'=>'CATE_NAME'],
- [['sort'], 'integer', 'min'=>'0', 'max'=>'99'],
- ];
- }
- public function attributeLabels()
- {
- return [
- 'id' => 'ID',
- 'cateName' => '分类名称',
- 'sort' => '排序',
- ];
- }
- /**
- * 指定校验场景
- * @return array
- */
- public function scenarios()
- {
- $parentScenarios = parent::scenarios();
- $customScenarios = [
- 'add' => ['cateName'],
- 'sort' => ['id', 'sort'],
- ];
- return array_merge($parentScenarios, $customScenarios);
- }
- /**
- * 申请
- * @return ArticleCategory|null
- * @throws \yii\db\Exception
- */
- public function edit(){
- if(!$this->validate()){
- return null;
- }
- $db = \Yii::$app->db;
- $transaction = $db->beginTransaction();
- try {
- $model = new ArticleCategory();
- $model->CATE_NAME = $this->cateName;
- $model->STATUS = 1;
- $model->CREATED_AT = Date::nowTime();
- if(!$model->save()){
- throw new Exception(Form::formatErrorsForApi($model->getErrors()));
- }
- $transaction->commit();
- } catch (Exception $e) {
- $transaction->rollBack();
- $this->addError('edit', $e->getMessage());
- return null;
- }
- return $model;
- }
- /**
- * 排序
- * @return ArticleCategory|null
- */
- public function sortTo(){
- if(!$this->validate()){
- return null;
- }
- $model = ArticleCategory::findOne(['ID'=>$this->id]);
- $model->SORT = $this->sort;
- if(!$model->save()){
- $this->addError('sortTo', Form::formatErrorsForApi($model->getErrors()));
- return null;
- }
- return $model;
- }
- }
|