_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; } }