'Country', 'freight' => 'Freight', 'free_shipping' => 'FreeShipping', ]; } /** * 指定场景 * @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')); } } /** * 设置运费模板. * @return true */ public function setTransportation(): ?bool { if (!$this->validate()) { return null; } $transaction = \Yii::$app->db->beginTransaction(); try { // 删除旧数据 $this->modelClass::deleteOne($this->countryId); // 添加/修改数据 $model = new FreeTemplate(); $model->ID = PageSnowFake::instance()->generateId(); $model->country_id = $this->countryId; $model->freight = $this->freight; $model->free_shipping = $this->freeShipping; if (!$model->save()) { $transaction->rollBack(); throw new Exception(Form::formatErrorsForApi($model->getErrors())); } $transaction->commit(); } catch (Exception $e) { $transaction->rollBack(); $this->addError('setTransportation', $e->getMessage()); return null; } return true; } }