FreeTemplateForm.php 2.4 KB

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