/**
  * @param CActiveRecord $model
  * @param $sortableAttribute
  * @param $sortOrderData
  *
  * @return string
  */
 private function update($model, $sortableAttribute, $sortOrderData)
 {
     $pk = $model->tableSchema->primaryKey;
     $pk_array = array();
     if (is_array($pk)) {
         // composite key
         $string_ids = array_keys($sortOrderData);
         $array_ids = array();
         foreach ($string_ids as $string_id) {
             $array_ids[] = explode(',', $string_id);
         }
         foreach ($array_ids as $array_id) {
             $pk_array[] = array_combine($pk, $array_id);
         }
     } else {
         // normal key
         $pk_array = array_keys($sortOrderData);
     }
     $models = $model->model()->findAllByPk($pk_array);
     $transaction = Yii::app()->db->beginTransaction();
     try {
         foreach ($models as $model) {
             $_key = is_array($pk) ? implode(',', array_values($model->primaryKey)) : $model->primaryKey;
             $model->{$sortableAttribute} = $sortOrderData[$_key];
             $model->save();
         }
         $transaction->commit();
     } catch (Exception $e) {
         // an exception is raised if a query fails
         $transaction->rollback();
     }
 }
示例#2
0
 /**
  * @param CActiveRecord $record
  * @param string        $colName
  * @param string        $newValue
  */
 protected function checkUpdatedAtField(CActiveRecord $record, $colName = 'name', $newValue = 'xxxxx')
 {
     $oldColumnValue = $record->{$colName};
     // Modifier l'objet met le champ updated_at à jour
     $oldUpdatedAt = $record->updated_at;
     $record->{$colName} = $newValue;
     $this->assertTrue($record->save());
     $this->assertNotEquals($oldUpdatedAt, $record->updated_at);
     // restauration de la valeur de départ
     $record->{$colName} = $oldColumnValue;
     $this->assertTrue($record->save());
 }
示例#3
0
 /**
  * Переопределенная функция сохранения группы LDAP.
  * Помимо сохранения данных группы LDAP, присваиваются выбранные права доступа
  * 
  * @param type $runValidation
  * @param type $attributes
  * @throws CHttpException
  */
 public function Save($runValidation = true, $attributes = null)
 {
     /* $selectedRows - массив выбранных ролей группы LDAP */
     $selectedRows = (string) filter_input(INPUT_POST, 'items') !== '' ? json_decode((string) filter_input(INPUT_POST, 'items'), true) : [];
     /* $_POST['oper'] может быть "edit" или "add", редактирование или добавление новой записи */
     if ((string) filter_input(INPUT_POST, 'oper') === '') {
         throw new CHttpException(500, 'Отсутствует POST переменная "oper"');
     }
     /* ИД группы LDAP, который редактируется, если необходим */
     $editid = (string) filter_input(INPUT_POST, 'editid');
     $oper = (string) filter_input(INPUT_POST, 'oper');
     if ($oper === 'edit' && $editid === '') {
         throw new CHttpException(500, 'Отсутствует POST переменная "editid"');
     }
     /* Сохраняем модель группы LDAP и присваиваем роли */
     if (parent::save($runValidation, $attributes) !== false) {
         /*  $auth = Yii::app()->authManager; */
         /* Удаляем все роли группы LDAP при сохранении изменений профиля групп LDAP */
         if ($editid !== '') {
             AuthAssignmentLdap::model()->deleteAll('groupid = :groupid', array(':groupid' => $editid));
         }
         /* Присваиваем выбранные роли группе LDAP */
         if ($editid === '' && $oper === 'add') {
             $editid = parent::getPrimaryKey();
         }
         if (count((array) $selectedRows) > 0) {
             foreach (array_keys($selectedRows) as $AuthItem) {
                 $model = new AuthAssignmentLdap();
                 $model->itemname = $AuthItem;
                 $model->groupid = $editid;
                 $model->save();
             }
         }
     }
 }
示例#4
0
 /**
  * Assert thet the model can be saved without error and, if errors are present, print
  * out the corresponding error messages.
  * @param CActiveRecord $model
  */
 public function assertSaves(CActiveRecord $model)
 {
     $saved = $model->save();
     if ($model->hasErrors()) {
         VERBOSE_MODE && print_r($model->getErrors());
     }
     $this->assertTrue($saved);
 }
示例#5
0
 public function save($runValidation = true, $attributes = null)
 {
     if (in_array($this->tableName(), array('{{post}}', '{{onlinehelp}}'))) {
         Yii::app()->user->setFlash('warning', '<strong>' . Yii::t('site', 'Info') . '</strong><br />' . Yii::t('site', 'Not allowed to save items in table {tableName} in this demo version.', array('{tableName}' => str_replace(array('{{', '}}'), array('', ''), $this->tableName()))));
         return true;
     }
     return parent::save($runValidation, $attributes);
 }
 public function saveActiveRecord(CActiveRecord $record)
 {
     try {
         if (!$record->save()) {
             new \Error(5, null, json_encode($record->getErrors()));
         }
     } catch (Exception $e) {
         new \Error(5, null, $e->getMesaage());
     }
 }
示例#7
0
 public function save($runValidation = true, $attributes = null)
 {
     parent::save($runValidation, $attributes);
     if ($this->rank == null) {
         $this->rank = $this->id;
         $this->setIsNewRecord(false);
         $this->save(false);
     }
     return true;
 }
 /**
  * Attempts to save the specified model with attribute values from POST. If 
  * the saving fails or if no POST data is available it returns false.
  * @param CActiveRecord $model the model
  * @return boolean whether the model was saved
  */
 protected function saveFromPost(&$model)
 {
     if (isset($_POST[$this->getModelClass()])) {
         $model->attributes = $_POST[$this->getModelClass()];
         if ($model->save()) {
             return true;
         }
     }
     return false;
 }
示例#9
0
 public function save($runValidation = true, $attributes = NULL)
 {
     $status = parent::save($runValidation, $attributes);
     if (!$this->getIsInversed()) {
         $inversed = new Contact();
         $inversed->user_id = $this->contact_id;
         $inversed->contact_id = $this->user_id;
         $inversed->save(false);
     }
     return $status;
 }
示例#10
0
文件: Files.php 项目: hkhateb/linet3
 public function save($runValidation = true, $attributes = NULL)
 {
     $a = parent::save($runValidation, $attributes);
     if ($this->public && $this->hash == '') {
         $download = new Download();
         $download->file_id = $this->id;
         $download->company_id = Yii::app()->user->Company;
         $this->hash = $download->id = md5(mt_rand());
         $download->save();
     }
     return $a;
 }
示例#11
0
 public function save($runValidation = true, $attributes = null)
 {
     // Save default store
     if ($this->store_id === 0) {
         Yii::app()->settings->setValue('config_title', $this->name);
         //TODO: Add additional fields here
         return true;
     } else {
         parent::save($runValidation, $attributes);
         //TODO: Add additional config fields here
     }
 }
示例#12
0
 public function save($runValidation = true, $attributes = null)
 {
     $user = Yii::app()->user;
     if ($user instanceof CWebUser) {
         $model = self::model()->find(['scopes' => ['active'], 'condition' => 'user_id=:userId AND token=:token AND platform=:platform', 'params' => [':userId' => $user->id, ':token' => $this->token, ':platform' => $this->platform]]);
         if ($model instanceof PushDevice) {
             $this->setIsNewRecord(false);
             $this->setPrimaryKey($model->id);
         }
     }
     return parent::save($runValidation, $attributes);
 }
示例#13
0
 /**
  *### .update()
  *
  * main function called to update column in database
  *
  */
 public function update()
 {
     //get params from request
     $this->primaryKey = yii::app()->request->getParam('pk');
     $this->attribute = yii::app()->request->getParam('name');
     $this->value = yii::app()->request->getParam('value');
     //checking params
     if (empty($this->attribute)) {
         throw new CException(Yii::t('TbEditableSaver.editable', 'Property "attribute" should be defined.'));
     }
     if (empty($this->primaryKey)) {
         throw new CException(Yii::t('TbEditableSaver.editable', 'Property "primaryKey" should be defined.'));
     }
     //loading model
     $this->model = CActiveRecord::model($this->modelClass)->findByPk($this->primaryKey);
     if (!$this->model) {
         throw new CException(Yii::t('TbEditableSaver.editable', 'Model {class} not found by primary key "{pk}"', array('{class}' => get_class($this->model), '{pk}' => is_array($this->primaryKey) ? CJSON::encode($this->primaryKey) : $this->primaryKey)));
     }
     //set scenario
     $this->model->setScenario($this->scenario);
     //commented to be able to work with virtual attributes
     //see https://github.com/vitalets/yii-bootstrap-editable/issues/15
     /*
     //is attribute exists
     if (!$this->model->hasAttribute($this->attribute)) {
     	throw new CException(Yii::t('EditableSaver.editable', 'Model {class} does not have attribute "{attr}"', array(
     	  '{class}'=>get_class($this->model), '{attr}'=>$this->attribute)));
     }
     */
     //is attribute safe
     if (!$this->model->isAttributeSafe($this->attribute)) {
         throw new CException(Yii::t('editable', 'Model {class} rules do not allow to update attribute "{attr}"', array('{class}' => get_class($this->model), '{attr}' => $this->attribute)));
     }
     //setting new value
     $this->setAttribute($this->attribute, $this->value);
     //validate attribute
     $this->model->validate(array($this->attribute));
     $this->checkErrors();
     //trigger beforeUpdate event
     $this->beforeUpdate();
     $this->checkErrors();
     //saving (no validation, only changed attributes)
     if ($this->model->save(false, $this->changedAttributes)) {
         //trigger afterUpdate event
         $this->afterUpdate();
     } else {
         $this->error(Yii::t('TbEditableSaver.editable', 'Error while saving record!'));
     }
 }
示例#14
0
 public function save($runValidation = TRUE, $attributes = NULL)
 {
     if ($this->is_active === NULL || $this->is_active == 0) {
         $this->is_active = $this::ACCOUNT_TEAM_MEMBER_IS_DEACTIVATED;
     }
     // check permission
     //		if (!$this->accepting_invitation)
     //		{
     //			if ($this->isNewRecord && !Permission::checkPermission($this, PERMISSION_ACCOUNT_TEAM_MEMBER_CREATE))
     //				return false;
     //			if (!$this->isNewRecord && !Permission::checkPermission($this, PERMISSION_ACCOUNT_TEAM_MEMBER_UPDATE))
     //				return false;
     //		}
     return parent::save($runValidation, $attributes);
 }
示例#15
0
 public function save($runValidation = true, $attributes = NULL)
 {
     $users = User::model()->findAll();
     parent::save($runValidation, $attributes);
     foreach ($users as $user) {
         if (!UserIncomeMap::model()->findByPk(array('user_id' => $user->id, 'itemVatCat_id' => $this->id))) {
             //'user_id', 'itemVatCat_id'
             $model = new UserIncomeMap();
             $attr = array("user_id" => $user->id, "itemVatCat_id" => $this->id, "account_id" => 100);
             $model->attributes = $attr;
             if (!$model->save()) {
                 return false;
             }
         }
     }
 }
示例#16
0
 /**
  * main function called to update column in database
  *
  */
 public function update()
 {
     //set params from request
     $this->primaryKey = yii::app()->request->getParam('pk');
     $this->attribute = yii::app()->request->getParam('name');
     $value = Yii::app()->request->getParam('value');
     //checking params
     if (empty($this->attribute)) {
         throw new CException(Yii::t('zii', 'Property "attribute" should be defined.'));
     }
     if (empty($this->primaryKey)) {
         throw new CException(Yii::t('zii', 'Property "primaryKey" should be defined.'));
     }
     //loading model
     $this->model = CActiveRecord::model($this->modelClass)->findByPk($this->primaryKey);
     if (!$this->model) {
         throw new CException(Yii::t('editable', 'Model {class} not found by primary key "{pk}"', array('{class}' => get_class($this->model), '{pk}' => $this->primaryKey)));
     }
     $this->model->setScenario($this->scenario);
     //is attribute exists
     if (!$this->model->hasAttribute($this->attribute)) {
         throw new CException(Yii::t('editable', 'Model {class} does not have attribute "{attr}"', array('{class}' => get_class($this->model), '{attr}' => $this->attribute)));
     }
     //is attribute safe
     if (!$this->model->isAttributeSafe($this->attribute)) {
         throw new CException(Yii::t('zii', 'Model {class} rules do not allow to update attribute "{attr}"', array('{class}' => get_class($this->model), '{attr}' => $this->attribute)));
     }
     //setting new value
     $this->setAttribute($this->attribute, $value);
     //validate
     $this->model->validate(array($this->attribute));
     if ($this->model->hasErrors()) {
         $this->error($this->model->getError($this->attribute));
     }
     //save
     if ($this->beforeUpdate()) {
         //saving (only chnaged attributes)
         if ($this->model->save(false, $this->changedAttributes)) {
             $this->afterUpdate();
         } else {
             $this->error(Yii::t('zii', 'Error while saving record!'));
         }
     } else {
         $firstError = reset($this->model->getErrors());
         $this->error($firstError[0]);
     }
 }
示例#17
0
 /**
  * Save associated active record. Use beforeSave and afterValidate functions to
  * set extra attributues such as update time and id of authenticated model.
  * Validation runs both on API resource and active record.
  * @param boolean $validate
  * @return boolean
  */
 public function save($validate = true)
 {
     if ($validate && !$this->validate(null, false)) {
         return false;
     }
     if (!$this->beforeSave()) {
         return false;
     }
     $saved = $this->model->save(false);
     // some fields might be updated during save, we want to refresh the current
     // model before returning output
     $this->scenario = 'view';
     // TODO: is there a cleaner way?
     $this->loadFromModel($this->model);
     if ($saved) {
         $this->afterSave();
     }
     return true;
 }
示例#18
0
 /**
  * Переопределенная функция сохранения пользователя.
  * Помимо сохранения данных пользователя, присваиваются выбранные права доступа
  * 
  * @param type $runValidation
  * @param type $attributes
  * @throws CHttpException
  */
 public function Save($runValidation = true, $attributes = null)
 {
     /* $selectedRows - массив выбранных ролей пользователя */
     $selectedRows = (string) filter_input(INPUT_POST, 'items') !== '' ? json_decode((string) filter_input(INPUT_POST, 'items'), true) : [];
     /* $_POST['oper'] может быть "edit" или "add", редактирование или добавление новой записи */
     if ((string) filter_input(INPUT_POST, 'oper') === '') {
         throw new CHttpException(500, 'Отсутствует POST переменная "oper"');
     }
     /* ИД пользователя, который редактируется, если необходим */
     $editid = (string) filter_input(INPUT_POST, 'editid');
     if ((string) filter_input(INPUT_POST, 'oper') === 'edit' && $editid === '') {
         throw new CHttpException(500, 'Отсутствует POST переменная "editid"');
     }
     /* Имя сценария, может быть "NewUser" - проверяет введеный пароль и подтверждение на совпадение.
      * Используется при добавлении нового пользотваеля, или смене пароля */
     $scenario = (string) filter_input(INPUT_POST, 'scenario');
     if ($scenario === 'NewUser') {
         $this->password = CPasswordHelper::hashPassword($this->password);
     }
     /* Хэшируем новый пароль */
     /* Сохраняем модель пользователя и присваиваем роли */
     if (parent::save($runValidation, $attributes) !== false) {
         $auth = Yii::app()->authManager;
         /* Удаляем все роли пользователя при сохранении изменений профиля пользователя */
         if ($editid !== '' && $scenario === '') {
             $assigned_roles = Yii::app()->authManager->getAuthAssignments($editid);
             foreach (array_keys($assigned_roles) as $AuthItem) {
                 $auth->revoke($AuthItem, $editid);
             }
         }
         /* Присваиваем выбранные роли пользователю */
         if (count((array) $selectedRows) > 0) {
             foreach (array_keys($selectedRows) as $AuthItem) {
                 $auth->assign($AuthItem, parent::getPrimaryKey());
             }
             Yii::app()->authManager->save();
         }
     }
 }
示例#19
0
 /**
  * rewrite save to add transaction
  * @param bool $runValidation
  * @param null $attributes
  * @return bool
  * @throws CDbException
  * @author Lujie.Zhou(gao_lujie@live.cn, qq:821293064).
  */
 public function save($runValidation = true, $attributes = null)
 {
     $db = $this->getDbConnection();
     if ($db->getCurrentTransaction() === null) {
         $transaction = $db->beginTransaction();
     }
     try {
         $return = parent::save($runValidation, $attributes);
         if (isset($transaction)) {
             $transaction->commit();
         }
         return $return;
     } catch (Exception $e) {
         $this->addError('Exception', $e);
         if (isset($transaction)) {
             $transaction->rollback();
         } else {
             throw new CDbException('YActiveRecord Save Model Error', 0, $this);
         }
         return false;
     }
 }
 /**
  * @param \CActiveRecord $ar
  */
 public function assertSaveFailure($ar, $failedAttributes = null)
 {
     $this->assertFalse($ar->save(), 'Expected saving of AR ' . get_class($ar) . ' to fail.');
     if ($failedAttributes !== null) {
         $this->assertEquals($failedAttributes, array_keys($ar->getErrors()));
     }
 }
示例#21
0
 /**
  * Override save method as some behaviours invalidates the save even though it is valid
  * @param  boolean $runValidation
  * @param  array  $attributes
  * @return boolean whether the saving succeeds
  */
 public function save($runValidation = true, $attributes = null)
 {
     if (!parent::save($runValidation, $attributes)) {
         if (empty($this->errors)) {
             return true;
         } else {
             $e = new Exception();
             Yii::log('Error saving model ' . get_class($this) . ': ' . json_encode($this->errors) . ' with attributes: ' . json_encode($this->attributes) . ' ' . $e->getTraceAsString(), 'error');
             return false;
         }
     } else {
         return true;
     }
 }
示例#22
0
 public function save($runValidation = true, $attributes = null)
 {
     if ($attributes === null) {
         $attributes = array('menuid', 'nestedconfig', 'visible', 'locked', 'sortposition', 'maxdepth', 'descriptionashint', 'scenarios', 'userroles', 'adminroles', 'url', 'icon', 'created', 'createduser', 'modified', 'modifieduser');
     }
     return parent::save($runValidation, $attributes);
 }
示例#23
0
 /**
  * install the cronjob on its cron table
  * @param CActiveRecord $cTable
  * @param string $name
  * @param int $lapse
  * @return bool
  */
 private final function installCron(CActiveRecord $cTable, $name, $lapse)
 {
     if (!is_numeric($lapse)) {
         return false;
     }
     $cTable->name = $name;
     $cTable->lapse = (int) $lapse;
     if ($cTable->save()) {
         return true;
     } else {
         return false;
     }
 }
示例#24
0
 /**
  *
  * @param boolean $runValidation
  * @param array $attributes
  * @return boolean 
  */
 public function save($runValidation = true, $attributes = NULL)
 {
     if (CStubActiveRecord::isUnittests()) {
         return CallFactory::call($this, 'save');
     }
     return parent::save($runValidation, $attributes);
 }
示例#25
0
 /**
  * Assert thet the model can be saved without error and, if errors are present, print
  * out the corresponding error messages.
  * @param CActiveRecord $model
  */
 public function assertSaves(CActiveRecord $model)
 {
     $saved = $model->save();
     if ($model->hasErrors()) {
         X2_TEST_DEBUG_LEVEL > 1 && print_r($model->getErrors());
     }
     $this->assertTrue($saved);
 }
示例#26
0
文件: Mail.php 项目: hkhateb/linet3
 public function save($runValidation = true, $attributes = NULL)
 {
     //$this->mailsend();
     return parent::save($runValidation, $attributes);
 }
 /**
  * Sets the language settings for the user
  * @param CActiveRecord $user
  */
 private function _setLanguageSettings($user)
 {
     if (Yii::app()->request->getPost('loginlang', 'default') != 'default') {
         $user->lang = sanitize_languagecode(Yii::app()->request->getPost('loginlang'));
         $user->save();
         $sLanguage = $user->lang;
     } else {
         if ($user->lang == 'auto' || $user->lang == '') {
             $sLanguage = getBrowserLanguage();
         } else {
             $sLanguage = $user->lang;
         }
     }
     Yii::app()->session['adminlang'] = $sLanguage;
     $this->getController()->lang = new limesurvey_lang($sLanguage);
 }
 /**
  * @param boolean $runValidation
  * @param array $attributes
  * @param boolean $allow_overriding - if true allows created/modified user/date to be set and saved via the model (otherwise gets overriden)
  * @return boolean
  */
 public function save($runValidation = true, $attributes = null, $allow_overriding = false)
 {
     $user_id = null;
     try {
         if (isset(Yii::app()->user)) {
             $user_id = Yii::app()->user->id;
         }
     } catch (Exception $e) {
     }
     if ($this->getIsNewRecord() || !isset($this->id)) {
         if (!$allow_overriding) {
             // Set creation properties
             if ($user_id === NULL) {
                 // Revert to the admin user
                 $this->created_user_id = 1;
             } else {
                 $this->created_user_id = $user_id;
             }
         }
         if (!$allow_overriding || $this->created_date == "1900-01-01 00:00:00") {
             $this->created_date = date('Y-m-d H:i:s');
         }
     }
     try {
         if (!$allow_overriding) {
             // Set the last_modified_user_id and last_modified_date fields
             if ($user_id === NULL) {
                 // Revert to the admin user
                 // need this try/catch block here to make older migrations pass with this hook in place
                 $this->last_modified_user_id = 1;
             } else {
                 $this->last_modified_user_id = $user_id;
             }
         }
         if (!$allow_overriding || $this->last_modified_date == "1900-01-01 00:00:00") {
             $this->last_modified_date = date('Y-m-d H:i:s');
         }
     } catch (Exception $e) {
     }
     return parent::save($runValidation, $attributes);
 }
示例#29
0
 public function save($runValidation = false, $attributes = null)
 {
     if ($this->isNewRecord) {
         $numSlides = $this->model()->count();
         if ($this->position != $numSlides) {
             Yii::log("Repositioning");
             $q = "UPDATE\n  tbl_slide\nSET\n  position = position + 1\nWHERE\n  position >= :newPosition\n";
             $newPosition = $this->position;
             $cmd = Yii::app()->db->createCommand($q);
             $cmd->bindParam(':newPosition', $newPosition, PDO::PARAM_INT);
             $cmd->execute();
         }
     } else {
         if ($this->oldPosition != null && $this->position != $this->oldPosition) {
             $q = "UPDATE\n  tbl_slide\nSET\n  position =\n  CASE\n  WHEN position = :oldPosition THEN :newPosition\n  ELSE IF(:newPosition > :oldPosition, position - 1, position + 1)\n  END\nWHERE\n  position BETWEEN LEAST(:newPosition, :oldPosition) AND GREATEST(:newPosition, :oldPosition)\n";
             $newPosition = $this->position;
             $cmd = Yii::app()->db->createCommand($q);
             $cmd->bindParam(':newPosition', $newPosition, PDO::PARAM_INT);
             $cmd->bindParam(':oldPosition', $this->oldPosition, PDO::PARAM_INT);
             $cmd->execute();
         }
     }
     if (empty($this->caption)) {
         $this->caption = " ";
     }
     return parent::save($runValidation, $attributes);
 }
示例#30
0
 /**
  * Save record to the database (update/add)
  * Basically, this parent method covers basic fields that the children shouldn't need to care.
  * These are: created date, created by, last update date, last updated by, subscription id, etc.
  * 
  * @return boolean success or failure of the operation
  * @access public
  */
 function save($runValidation = true, $attributes = NULL)
 {
     $new_record = $this->isNewRecord;
     $now = date('Y-m-d H:i:s');
     $result = parent::save($runValidation, $attributes);
     if ($result) {
         /**
          * set values for new record in CoreEntity
          */
         $coreEntity = $this->getCoreEntity();
         if ($new_record || $coreEntity === null) {
             $coreEntity = new LbCoreEntity();
             $coreEntity->lb_entity_type = $this->getEntityType();
             $coreEntity->lb_entity_primary_key = $this->lb_record_primary_key;
             $coreEntity->lb_created_by = Yii::app()->user->id;
             $coreEntity->lb_created_date = $now;
         } else {
         }
         $coreEntity->lb_last_updated_by = Yii::app()->user->id;
         $coreEntity->lb_last_update = $now;
         $coreEntity->lb_subscription_id = LBApplication::getCurrentlySelectedSubscription();
         $coreEntity->lb_locked_from_deletion = self::RECORD_NOT_LOCKED_FROM_DELETION;
         $coreEntity->save();
     }
     return $result;
 }