/** * @param Market_OrderStatusModel $model * @param array $emailsIds * * @return bool * @throws Exception * @throws \CDbException * @throws \Exception */ public function save(Market_OrderStatusModel $model, array $emailsIds) { if ($model->id) { $record = Market_OrderStatusRecord::model()->findById($model->id); if (!$record->id) { throw new Exception(Craft::t('No order status exists with the ID “{id}”', ['id' => $model->id])); } } else { $record = new Market_OrderStatusRecord(); } $record->name = $model->name; $record->handle = $model->handle; $record->color = $model->color; $record->default = $model->default; $record->validate(); $model->addErrors($record->getErrors()); //validating emails ids $criteria = new \CDbCriteria(); $criteria->addInCondition('id', $emailsIds); $exist = Market_EmailRecord::model()->exists($criteria); $hasEmails = (bool) count($emailsIds); if (!$exist && $hasEmails) { $model->addError('emails', 'One or more emails do not exist in the system.'); } //saving if (!$model->hasErrors()) { MarketDbHelper::beginStackedTransaction(); try { //only one default status can be among statuses of one order type if ($record->default) { Market_OrderStatusRecord::model()->updateAll(['default' => 0]); } // Save it! $record->save(false); //Delete old links if ($model->id) { Market_OrderStatusEmailRecord::model()->deleteAllByAttributes(['orderStatusId' => $model->id]); } //Save new links $rows = array_map(function ($id) use($record) { return [$id, $record->id]; }, $emailsIds); $cols = ['emailId', 'orderStatusId']; $table = Market_OrderStatusEmailRecord::model()->getTableName(); craft()->db->createCommand()->insertAll($table, $cols, $rows); // Now that we have a calendar ID, save it on the model $model->id = $record->id; MarketDbHelper::commitStackedTransaction(); } catch (\Exception $e) { MarketDbHelper::rollbackStackedTransaction(); throw $e; } return true; } else { return false; } }