FreeTemplateForm.php 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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. public $currencyId;
  17. /**
  18. * @inheritdoc
  19. */
  20. public function rules()
  21. {
  22. return [
  23. [['countryId', 'freight', 'freeShipping'], 'required'],
  24. [['countryId'], 'isCountry'],
  25. ];
  26. }
  27. public function attributeLabels()
  28. {
  29. return [
  30. 'country_id' => 'Country',
  31. 'freight' => 'Freight',
  32. 'free_shipping' => 'FreeShipping',
  33. 'currency_id' => 'currency',
  34. ];
  35. }
  36. /**
  37. * 指定场景
  38. * @return array
  39. */
  40. public function scenarios()
  41. {
  42. $parentScenarios = parent::scenarios();
  43. $customScenarios = [
  44. 'setTransportation' => ['countryId', 'freight', 'freeShipping'],
  45. ];
  46. return array_merge($parentScenarios, $customScenarios);
  47. }
  48. public function isCountry($attribute){
  49. $country = Countries::getById($this->countryId);
  50. if (!$country) {
  51. $this->addError($attribute, Yii::t('ctx', 'countryDoesNotExist'));
  52. }
  53. $this->currencyId = $country['LOCAL_CURRENCY_ID'];
  54. }
  55. /**
  56. * 设置运费模板.
  57. * @return true
  58. */
  59. public function setTransportation(): ?bool
  60. {
  61. if (!$this->validate()) {
  62. return null;
  63. }
  64. $transaction = \Yii::$app->db->beginTransaction();
  65. try {
  66. // 删除旧数据
  67. $this->modelClass::deleteOne($this->countryId);
  68. // 添加/修改数据
  69. $model = new FreeTemplate();
  70. $model->ID = PageSnowFake::instance()->generateId();
  71. $model->country_id = $this->countryId;
  72. $model->freight = $this->freight;
  73. $model->free_shipping = $this->freeShipping;
  74. $model->currency_id = $this->currencyId;
  75. if (!$model->save()) {
  76. $transaction->rollBack();
  77. throw new Exception(Form::formatErrorsForApi($model->getErrors()));
  78. }
  79. $transaction->commit();
  80. } catch (Exception $e) {
  81. $transaction->rollBack();
  82. $this->addError('setTransportation', $e->getMessage());
  83. return null;
  84. }
  85. return true;
  86. }
  87. }