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