ArticleCategoryForm.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. <?php
  2. namespace common\models\forms;
  3. use common\helpers\Date;
  4. use common\components\Model;
  5. use common\helpers\Form;
  6. use common\models\ArticleCategory;
  7. use yii\base\Exception;
  8. /**
  9. * Login form
  10. */
  11. class ArticleCategoryForm extends Model
  12. {
  13. public $id;
  14. public $cateName;
  15. public $sort;
  16. /**
  17. * @inheritdoc
  18. */
  19. public function rules()
  20. {
  21. return [
  22. [['id', 'cateName', 'sort'], 'trim'],
  23. [['id', 'cateName', 'sort'], 'required'],
  24. [['id'], 'exist', 'targetClass'=>ArticleCategory::class, 'targetAttribute'=>'ID'],
  25. [['cateName'], 'unique', 'targetClass'=>ArticleCategory::class, 'targetAttribute'=>'CATE_NAME'],
  26. [['sort'], 'integer', 'min'=>'0', 'max'=>'99'],
  27. ];
  28. }
  29. public function attributeLabels()
  30. {
  31. return [
  32. 'id' => 'ID',
  33. 'cateName' => '分类名称',
  34. 'sort' => '排序',
  35. ];
  36. }
  37. /**
  38. * 指定校验场景
  39. * @return array
  40. */
  41. public function scenarios()
  42. {
  43. $parentScenarios = parent::scenarios();
  44. $customScenarios = [
  45. 'add' => ['cateName'],
  46. 'sort' => ['id', 'sort'],
  47. ];
  48. return array_merge($parentScenarios, $customScenarios);
  49. }
  50. /**
  51. * 申请
  52. * @return ArticleCategory|null
  53. * @throws \yii\db\Exception
  54. */
  55. public function edit(){
  56. if(!$this->validate()){
  57. return null;
  58. }
  59. $db = \Yii::$app->db;
  60. $transaction = $db->beginTransaction();
  61. try {
  62. $model = new ArticleCategory();
  63. $model->CATE_NAME = $this->cateName;
  64. $model->STATUS = 1;
  65. $model->CREATED_AT = Date::nowTime();
  66. if(!$model->save()){
  67. throw new Exception(Form::formatErrorsForApi($model->getErrors()));
  68. }
  69. $transaction->commit();
  70. } catch (Exception $e) {
  71. $transaction->rollBack();
  72. $this->addError('edit', $e->getMessage());
  73. return null;
  74. }
  75. return $model;
  76. }
  77. /**
  78. * 排序
  79. * @return ArticleCategory|null
  80. */
  81. public function sortTo(){
  82. if(!$this->validate()){
  83. return null;
  84. }
  85. $model = ArticleCategory::findOne(['ID'=>$this->id]);
  86. $model->SORT = $this->sort;
  87. if(!$model->save()){
  88. $this->addError('sortTo', Form::formatErrorsForApi($model->getErrors()));
  89. return null;
  90. }
  91. return $model;
  92. }
  93. }