| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100 |
- <?php
- namespace common\models\forms;
- use common\components\Model;
- use common\helpers\Form;
- use common\models\Countries;
- use common\models\FreeTemplate;
- use Yii;
- use yii\base\Exception;
- class FreeTemplateForm extends Model
- {
- public $countryId;
- public $freight;
- public $freeShipping;
- public $currencyId;
- private $_model;
- public function init() {
- parent::init();
- $this->_model = FreeTemplate::findOne(['country_id' => $this->countryId]) ?: new FreeTemplate();
- }
- /**
- * @inheritdoc
- */
- public function rules()
- {
- return [
- [['countryId', 'freight', 'freeShipping'], 'required'],
- [['countryId'], 'isCountry'],
- ];
- }
- public function attributeLabels()
- {
- return [
- 'country_id' => 'Country',
- 'freight' => 'Freight',
- 'free_shipping' => 'FreeShipping',
- 'currency_id' => 'currency',
- ];
- }
- /**
- * 指定场景
- * @return array
- */
- public function scenarios()
- {
- $parentScenarios = parent::scenarios();
- $customScenarios = [
- 'setTransportation' => ['countryId', 'freight', 'freeShipping'],
- ];
- return array_merge($parentScenarios, $customScenarios);
- }
- public function isCountry($attribute){
- $country = Countries::getById($this->countryId);
- if (!$country) {
- $this->addError($attribute, Yii::t('ctx', 'countryDoesNotExist'));
- }
- $this->currencyId = $country['LOCAL_CURRENCY_ID'];
- }
- /**
- * 设置运费模板.
- * @return true
- */
- public function setTransportation(): ?bool
- {
- if (!$this->validate()) {
- return null;
- }
- $transaction = \Yii::$app->db->beginTransaction();
- try {
- // 添加/修改数据
- $this->_model->country_id = $this->countryId;
- $this->_model->freight = $this->freight;
- $this->_model->free_shipping = $this->freeShipping;
- $this->_model->currency_id = $this->currencyId;
- if (!$this->_model->save()) {
- $transaction->rollBack();
- throw new Exception(Form::formatErrorsForApi($this->_model->getErrors()));
- }
- $transaction->commit();
- } catch (Exception $e) {
- $transaction->rollBack();
- $this->addError('setTransportation', $e->getMessage());
- return null;
- }
- return true;
- }
- }
|