| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495 |
- <?php
- namespace common\models\forms;
- use common\components\Model;
- use common\helpers\Form;
- use common\helpers\snowflake\PageSnowFake;
- use common\models\Countries;
- use common\models\FreeTemplate;
- use Yii;
- use yii\base\Exception;
- class FreeTemplateForm extends Model
- {
- public $modelClass = FreeTemplate::class;
- public $countryId;
- public $freight;
- public $freeShipping;
- /**
- * @inheritdoc
- */
- public function rules()
- {
- return [
- [['countryId', 'freight', 'freeShipping'], 'required'],
- [['countryId'], 'isCountry'],
- ];
- }
- public function attributeLabels()
- {
- return [
- 'country_id' => '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;
- }
- }
|