FreeTemplateForm.php 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  1. <?php
  2. namespace common\models\forms;
  3. use common\components\Model;
  4. use common\helpers\Form;
  5. use common\helpers\snowflake\PageSnowFake;
  6. use common\models\Countries;
  7. use common\models\FreeTemplate;
  8. use Yii;
  9. use yii\base\Exception;
  10. class FreeTemplateForm extends Model
  11. {
  12. public $modelClass = FreeTemplate::class;
  13. public $countryId;
  14. public $freight;
  15. public $freeShipping;
  16. /**
  17. * @inheritdoc
  18. */
  19. public function rules()
  20. {
  21. return [
  22. [['countryId', 'freight', 'freeShipping'], 'required'],
  23. [['countryId'], 'isCountry'],
  24. ];
  25. }
  26. public function attributeLabels()
  27. {
  28. return [
  29. 'country_id' => 'Country',
  30. 'freight' => 'Freight',
  31. 'free_shipping' => 'FreeShipping',
  32. ];
  33. }
  34. /**
  35. * 指定场景
  36. * @return array
  37. */
  38. public function scenarios()
  39. {
  40. $parentScenarios = parent::scenarios();
  41. $customScenarios = [
  42. 'setTransportation' => ['countryId', 'freight', 'freeShipping'],
  43. ];
  44. return array_merge($parentScenarios, $customScenarios);
  45. }
  46. public function isCountry($attribute){
  47. $country = Countries::getById($this->countryId);
  48. if (!$country) {
  49. $this->addError($attribute, Yii::t('ctx', 'countryDoesNotExist'));
  50. }
  51. }
  52. /**
  53. * 设置运费模板.
  54. * @return true
  55. */
  56. public function setTransportation(): ?bool
  57. {
  58. if (!$this->validate()) {
  59. return null;
  60. }
  61. $transaction = \Yii::$app->db->beginTransaction();
  62. try {
  63. // 删除旧数据
  64. $this->modelClass::deleteOne($this->countryId);
  65. // 添加/修改数据
  66. $model = new FreeTemplate();
  67. $model->ID = PageSnowFake::instance()->generateId();
  68. $model->country_id = $this->countryId;
  69. $model->freight = $this->freight;
  70. $model->free_shipping = $this->freeShipping;
  71. if (!$model->save()) {
  72. $transaction->rollBack();
  73. throw new Exception(Form::formatErrorsForApi($model->getErrors()));
  74. }
  75. $transaction->commit();
  76. } catch (Exception $e) {
  77. $transaction->rollBack();
  78. $this->addError('setTransportation', $e->getMessage());
  79. return null;
  80. }
  81. return true;
  82. }
  83. }