/** * Saves the current model * @param boolean $runValidation whether to perform validation before saving the record. * If the validation fails, the record will not be saved to database. * @param array $attributeNames list of attribute names that need to be saved. Defaults to null, * meaning all attributes that are loaded from DB will be saved. * @param boolean $withSubtree whether subtree sticks to model (e.g. if model parent is changes - should subtree follow model or stay with model's parent) * @return boolean whether the saving succeeds */ public function save($runValidation = true, $attributeNames = null, $withSubtree = true) { $transaction = $this->getDb()->beginTransaction(); try { $result = false; if ($this->isNewRecord) { $this->setNodeLevel($this->calculateLevel()); if (parent::save($runValidation, $attributeNames)) { $this->setAncestorsLinks(); $result = true; } } else { if ($this->{$this->getIdParentAttribute()} != $this->getOldParentId() && $this->prepareParentChange($withSubtree) && parent::save($runValidation, $attributeNames)) { $result = true; } } if ($result === true) { $transaction->commit(); return true; } else { $transaction->rollBack(); return false; } } catch (Exception $e) { $transaction->rollBack(); throw $e; } }
/** * @param ActiveRecord $model * @param array $params * @return bool|mixed */ public function performModelSave(ActiveRecord $model, array $params) { $ajax = Yii::$app->request->isAjax; if ($model->save()) { if ($ajax) { $data = ['success' => true, 'message' => Yii::t('management', 'Model saved')]; if (isset($params['success']) && is_callable($params['success'])) { $data = array_merge($data, call_user_func($params['success'], $model)); } return $this->sendJson($data); } if (isset($params['fallback']) && is_callable($params['fallback'])) { return call_user_func($params['fallback'], $model); } } else { if ($ajax) { $data = ['success' => false, 'message' => Yii::t('management', 'Model not saved'), 'messages' => ActiveForm::validate($model)]; if (isset($params['error']) && is_callable($params['error'])) { $data = array_merge($data, call_user_func($params['error'], $model)); } return $this->sendJson($data); } } return false; }
/** * @param boolean $runValidation * @throws RowException */ public function save($runValidation = true) { if ($runValidation) { $this->validate(); } $this->_instance->save(false); }
public function save($runValidation = true, $attributeNames = NULL) { $this->user_id = Yii::$app->getUser()->id; $this->created_at = time(); //$this->content = strip_tags($this->content); //去掉html标签 parent::save($runValidation, $attributeNames); }
public function save($runValidation = true, $attributeNames = null) { if ($this->tmpname != null) { rename("{$this->tempPath}/{$this->tmpname}", "{$this->basePath}/{$this->tmpname}"); $this->path = $this->tmpname; } return parent::save($runValidation, $attributeNames); }
/** * @param \yii\base\ModelEvent $event * @throws Exception */ public function createRecord($event) { foreach ($this->attributes as $key => $value) { if (is_string($value)) { $this->target->{$key} = ArrayHelper::getValue($event->sender, $value); } else { if (CheckHelper::isCallable($value)) { $this->target->{$key} = call_user_func($value, $event->sender); } else { throw new Exception(); } } } if (!$this->target->save()) { throw new Exception('Save target error: ' . Json::encode($this->target)); } }
public function save($runValidation = true, $attributeNames = null) { $result = parent::save($runValidation, $attributeNames); if ($result) { // При изменении препаратов, менять пользователя и дату изменения в карте глаукомного пациента Glaukuchet::findOne($this->id_glaukuchet)->UpdateChangeAttributes(); } return $result; }
/** * @param bool $runValidation * @param null $attributeNames * * @return bool|void */ public function save($runValidation = true, $attributeNames = null) { if ($this->getIsNewRecord()) { $this->date_create = date('Y-m-d H:i:s'); } if (is_null($this->date_execute)) { $this->date_execute = date('Y-m-d H:i:s'); } return parent::save($runValidation, $attributeNames); }
public function save($runValidation = true, $attributeNames = null) { if (!$this->history) { $this->history = []; } $oldUrl = $this->getOldAttribute('url'); if ($this->url !== $oldUrl) { $this->history += [$oldUrl]; } return parent::save($runValidation, $attributeNames); }
public function save($runValidation = true, $attributeNames = null) { if (parent::save($runValidation, $attributeNames)) { //dopo aver salvato le modifiche, processa gli upload delle foto foreach ($this->addimage as $tmpfoto) { $foto = new Foto(); $foto->cartellone = $this->id; $foto->tmpname = $tmpfoto; $foto->save(); } return true; } return false; }
/** * @param ActiveRecord $model */ private function processModel(ActiveRecord $model) { $model->detachBehaviors(); $count = $model->{$this->countRelation}(); if ($count instanceof ActiveQuery) { $count = $count->count(); } else { if (is_array($count)) { $count = json_encode($count); } } $model->{$this->columnToUpdate} = $count; $model->save(false, [$this->columnToUpdate]); }
public function save($runValidation = true, $attributeNames = NULL) { self::formatModel(); $new_assigned = ''; $send_notification = 0; if ($this->assigned == '1') { $new_assigned = \app\memoboard\functions::getArray($this->assigned_to); $send_notification = $this->send_notification; } $connection = \Yii::$app->db; $transaction = $connection->beginTransaction(); if (parent::save() && self::saveAssign($new_assigned, $send_notification)) { $transaction->commit(); return true; } $transaction->rollback(); return false; }
public function save($runValidation = true, $attributeNames = null) { $uploadedFile = UploadedFile::getInstance($this, 'preview'); if ($uploadedFile) { $filePath = 'uploads/' . $uploadedFile->baseName . '.' . $uploadedFile->extension; if (file_exists($filePath)) { $filePath = 'uploads/' . $uploadedFile->baseName . 'N.' . $uploadedFile->extension; } $uploadedFile->saveAs($filePath); $this->preview = '/' . $filePath; } else { $oldPreview = $this->getOldAttribute('preview'); if ($oldPreview) { $this->preview = $oldPreview; } } return parent::save($runValidation, $attributeNames); }
/** * @param $position * @return bool * @throws \yii\db\Exception */ public function insertTo($position) { if ($this->getValue() == $position) { return true; } // 59 -> 56 = 58 57 56 // 56 -> 59 = 57 58 59 $start = $this->getValue(); $end = $position; if ($start == null || $start == 0) { $this->setInsertSort(); $this->owner->save(); return true; } $direction = $start > $end ? static::DirectionDown : static::DirectionUp; $query = $this->getQuery(); $query->andWhere(['between', $this->attributeName, min($start, $end), max($start, $end)]); $query->getSortBehavior()->sort(); /** * @var ISortableActiveRecord[]|ActiveRecord[] $items */ $items = $query->all(); $transaction = $this->owner->getDb()->beginTransaction(); try { foreach ($items as $index => $item) { if ($item->getPrimaryKey() == $this->owner->getPrimaryKey()) { $item->getSortBehavior()->setSort($position); $item->save(); } else { $item->getSortBehavior()->setSort($item->getSortBehavior()->getValue() + ($direction == static::DirectionDown ? 1 : -1)); $item->save(); } } /* @TODO сделать фикс позиций, что бы не перескакивало и не было дублей */ $transaction->commit(); } catch (\Exception $ex) { $transaction->rollBack(); return false; } return true; }
/** * Store data record and track change statistics * * @param ActiveRecord $ActiveRecord * * @return bool false if not saved */ protected function storeDataRecord(ActiveRecord $ActiveRecord) { if ($ActiveRecord->getDirtyAttributes()) { $unsaved_record = clone $ActiveRecord; // Save record if (!$ActiveRecord->save()) { // Create error message $message = "Save error: " . json_encode($ActiveRecord->errors) . "\n"; $message .= "Record data: " . json_encode($ActiveRecord->getAttributes()) . "\n"; trigger_error($message, E_USER_WARNING); $this->incStat('error_' . $ActiveRecord->tableName()); return false; } // Store statistics if ($unsaved_record->isNewRecord) { $this->incStat('new_' . $ActiveRecord->tableName()); } else { $this->incStat('update_' . $ActiveRecord->tableName()); } } return true; }
public function save($runValidation = true, $attributeNames = null) { $date = date('Y-m-d', strtotime($this->transaction->date . " +1 day")); if ($this->isNewRecord) { if ($date >= '2015-11-01') { $balance = $this->account->getBalance($date); if ($balance->date != $date) { $balance = new Balance(); $balance->date = $date; $balance->account_id = $this->account->id; } $balance->sum = $this->account->getBalance($date)->sum - $this->sum; $balance->save(); $balance->updateFuture(-$this->sum); } else { // For previous records $balance = $this->account->getBalance($date); if (!$balance) { $balance = $this->account->getClosestFutureBalance($date); } if ($balance->date != $date) { $balance = new Balance(); $balance->date = $date; $balance->account_id = $this->account->id; } $balance->sum = $this->account->getBalance($date)->sum; $balance->save(); $balance->updatePast($this->sum); } } else { if ($date >= '2015-11-01') { // Substract previos from next balances // Add new to next balances $balance = $this->account->getBalance($date); if ($balance->date != $date) { $balance = new Balance(); $balance->date = $date; $balance->account_id = $this->account->id; } $balance->sum = $this->account->getBalance($date)->sum - $this->sum + $this->oldAttributes['sum']; $balance->save(); $balance->updateFuture(-$this->sum + $this->oldAttributes['sum']); } else { // } } return parent::save($runValidation, $attributeNames); }
/** * @param ActiveRecord $model * @return string|\yii\web\Response */ protected function editModel($model) { // validate() && save(false) because of CantSave exception if ($model->load(Yii::$app->request->post()) && $model->validate() && $model->save(false)) { return $this->redirect($this->getReturnUrl()); } else { return $this->render($this->formView, ['model' => $model, 'returnUrl' => $this->getReturnUrl(), 'modelTitleForms' => $this->modelTitleForms, 'formElements' => $this->getFormElements($model)]); } }
public function save($runValidation = true, $attributeNames = null) { \Yii::$app->cache->flush(); if (isset($this->parent_id) && $this->parent_id) { $parent = self::find()->where(['id' => $this->parent_id])->select('super_parent_id')->one(); $super_parent_id = $parent->super_parent_id ? $parent->super_parent_id : $this->parent_id; $this->super_parent_id = $super_parent_id; } return parent::save($runValidation, $attributeNames); }
/** * Send currently signed emails. */ protected function sendSigned() { while ($fetchedMails = $this->findMailBySignature($this->pageSize)) { foreach ($fetchedMails as $this->_fetchedMail) { if ($this->sentByBehavior) { $this->_fetchedMail->attachBehavior($this->sentByBehavior->className(), $this->sentByBehavior); } $msg = $this->assembleMailMessage($this->_fetchedMail); $isSent = $this->testMode ? rand(0, 1) : $this->getMailer()->send($msg); $this->processEmailStatus($this->_fetchedMail, $isSent); $this->_fetchedMail->save(false); $this->{$this->useLiteAntiSpams ? "applySpamRulesLite" : "applySpamRules"}(++$this->_sentCount); } } }
public function save($runValidation = true, $attributeNames = NULL) { $this->user_id = Yii::$app->getUser()->id; $this->status = 1; //后续可用此字段增加审核功能 return parent::save($runValidation, $attributeNames); }
/** * @inheritdoc */ public function save($runValidation = false, $attributeNames = null) { if ($this->isNewRecord) { //$this->date_login = '******'; //$this->date_modify = '0000-00-00 00:00:00'; $this->fecha_registro = Yii::$app->fn->GetDateTime(); } else { //$this->date_login = Yii::$app->fn->GetDateTime(); //$this->date_modify = Yii::$app->fn->GetDateTime(); } return parent::save($runValidation, $attributeNames); //return false; }
/** * @param array $link * @param ActiveRecord $foreignModel * @param ActiveRecord $primaryModel * @throws InvalidCallException */ private function bindModels($link, $foreignModel, $primaryModel) { foreach ($link as $fk => $pk) { $value = $primaryModel->{$pk}; if ($value === null) { throw new InvalidCallException('Unable to link models: the primary key of ' . get_class($primaryModel) . ' is null.'); } $foreignModel->{$fk} = $value; } $foreignModel->save(false); }
/** * @inheritdoc */ public function save($runValidation = true, $attributeNames = null) { $transaction = $this::getDb()->beginTransaction(); $_success = true; if (!$this->id) { $this->author_id = \Yii::$app->user->id; } $result = parent::save($runValidation, $attributeNames); if (!$result) { $_success = false; } foreach ($this->attributeValues as $key => $attribute) { $attribute->catalog_id = $this->id; $result = $attribute->save($runValidation); if ($attribute->errors) { $this->addError('attributeValues[' . $key . '][value]', $attribute->errors['value'][0]); } if (!$result) { $_success = false; } } !$_success ? $transaction->rollBack() : $transaction->commit(); return $_success; }
/** * Mise à jour de l'objet. * Si $saveRelated vaut 'true', la table d'association avec les tags est mise à jour en même temps. * * @param bool|true $runValidation * @param null $attributeNames * @param bool|false $saveRelated * @return bool */ public function save($runValidation = true, $attributeNames = null, $saveRelated = false) { $transaction = Yii::$app->db->beginTransaction(); try { if (!parent::save($runValidation, $attributeNames)) { throw new Exception('Erreur sur parent::save()'); } if ($saveRelated && !BaseNewsBaseTagQuery::updateBaseTagsForNews($this->baseTagsIds(), $this->updatedBaseTagsIds, $this->id)) { throw new Exception("Erreur lors de la mise à jour de la table d'association"); } } catch (Exception $x) { Yii::error($x->getMessage(), __METHOD__); $transaction->rollBack(); return false; } $transaction->commit(); return true; }
public function save($runValidation = true, $attributeNames = NULL) { $this->updated_at = date('Y-m-d H:i:s'); return parent::save($runValidation, $attributeNames); }
/** * Save model of settings * @param ActiveRecord $model Model to save * @param array $requestParams Request parameters * @return bool */ protected function saveSettingsModel(ActiveRecord $model, array $requestParams) { $success = false; $transaction = $model->getDb()->beginTransaction(); try { $model->load($requestParams); if ($model->save()) { $transaction->commit(); Yii::$app->interfaceSettings->refreshUserInterfaceSettings($model->user_id, $model->interface_id); $success = true; } else { throw new Exception(); } } catch (Exception $e) { if ($transaction->isActive) { $transaction->rollBack(); } } // trigger an event $this->trigger(self::EVENT_SAVE_SETTING, new ExtraDataEvent(['extraData' => ['model' => $model, 'success' => $success]])); return $success; }
/** * @return array relational rules. */ public function save($runValidation = true, $attributes = NULL) { //$this->id=0; if ($this->salt == '') { $this->salt = $this->generateSalt(); } if ($this->passwd != '') { $this->password = $this->hashPassword($this->passwd, $this->salt); } return parent::save($runValidation, $attributes); }
public function save($runValidation = true, $attributeNames = null) { $this->create_at = time(); $this->password = $this->getPwd($this->password); return parent::save(); }
public function unpublished() { if (!$this->beforePublish()) { return false; } \yii::trace($this->hasAttribute('state'), 'checkState'); if ($this->hasAttribute('state')) { $this->state = self::STATUS_UNPUBLISH; \yii::trace('set State::' . $this->statenames[$this->state], 'setState'); } $this->status = self::STATUS_UNPUBLISH; \yii::trace('set Status::' . $this->statusnames[$this->status], 'setStatus'); $isSave = parent::save(); if ($isSave) { $this->afterUnPublish(); } return $isSave; }
/** * Saves the model. * @param ActiveRecord $model * @return boolean whether the saving succeeds */ protected function saveModel($model) { return $model->save(); }