public function save() { parent::save(); /** * У сотрудников, которых нет приказов по * ГАК в году комиссии автоматически устанавливается * приказ от комиссии */ if ($this->order_id !== 0) { $persons = new CArrayList(); foreach ($this->members->getItems() as $person) { $persons->add($person->getId(), $person); } if (!is_null($this->manager)) { $persons->add($this->manager->getId(), $this->manager); } foreach ($persons->getItems() as $person) { if (is_null($person->getSABOrdersByYear($this->year))) { $ar = new CActiveRecord(array("id" => null, "person_id" => $person->getId(), "year_id" => $this->year->getId(), "order_id" => $this->order_id)); $ar->setTable(TABLE_SAB_PERSON_ORDERS); $ar->insert(); } } } }
/** * @param CActiveRecord $owner */ public function attach($owner) { $validator = new yupe\components\validators\NumberValidator(); $validator->attributes = array($this->priceAttribute, $this->priceEurAttribute, $this->priceOldAttribute); $owner->getValidatorList()->add($validator); parent::attach($owner); }
public function init() { parent::init(); if ($this->model === null) { $model = Yii::createComponent(array('class' => $this->formClass)); $model->objectId = $this->objectParameter->id_object; $model->parameterId = $this->objectParameter->id_parameter; if ($this->mainModel->isNewRecord) { if (!$this->mainModel->getTmpId()) { $this->mainModel->setTmpId($this->generateTmpId()); } $model->tmpId = $this->mainModel->getTmpId(); } else { $model->instanceId = $this->mainModel->getIdInstance(); } $this->model = $model; } if ($this->uploadTemplate === null) { $this->uploadTemplate = 'template-upload-' . $this->id; } if ($this->downloadTemplate === null) { $this->downloadTemplate = 'template-download-' . $this->id; } if (!isset($this->htmlOptions['id'])) { $this->htmlOptions['id'] = $this->id; } $this->options = CMap::mergeArray($this->options, array('formData' => $this->model->toRequestParams(), 'uploadTemplateId' => $this->uploadTemplate, 'downloadTemplateId' => $this->downloadTemplate)); if (!array_key_exists('previewMaxHeight', $this->options) && array_key_exists('height', $this->thumbConfig)) { $this->options['previewMaxHeight'] = $this->thumbConfig['height']; } if (!array_key_exists('previewMaxWidth', $this->options) && array_key_exists('width', $this->thumbConfig)) { $this->options['previewMaxWidth'] = $this->thumbConfig['width']; } }
/** * @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(); } }
public function save() { $this->grant->save(); /** * Работа с участниками */ $members = array(); if (array_key_exists("members", $this->_fields)) { $members = $this->_fields["members"]; } /** * Делаем руководителя тоже участником */ if ($this->grant->manager_id != "0") { $members[] = $this->grant->manager_id; } /** * Удаляем старых участников */ foreach (CActiveRecordProvider::getWithCondition(TABLE_GRANT_MEMBERS, "grant_id= " . $this->grant->getId())->getItems() as $ar) { $ar->remove(); } /** * Добавляем новых */ foreach ($members as $member) { $ar = new CActiveRecord(array("id" => null, "grant_id" => $this->grant->getId(), "person_id" => $member)); $ar->setTable(TABLE_GRANT_MEMBERS); $ar->insert(); } }
public function save() { $group = $this->group; $roles = array(); if (array_key_exists("roles", $group)) { $roles = $group["roles"]; unset($group["roles"]); } $groupObj = new CUserGroup(); $groupObj->setAttributes($group); /** * Удаляем старые задачи группы и пользователей */ foreach (CActiveRecordProvider::getWithCondition(TABLE_USER_GROUP_HAS_ROLES, "user_group_id = " . $groupObj->getId())->getItems() as $ar) { $ar->remove(); } $groupObj->save(); /** * Создаем новые задачи группы и пользователей */ foreach ($roles as $role => $level) { if ($level != 0) { $ar = new CActiveRecord(array("id" => null, "user_group_id" => $groupObj->getId(), "task_id" => $role, "task_rights_id" => $level)); $ar->setTable(TABLE_USER_GROUP_HAS_ROLES); $ar->insert(); } } }
/** * @param CActiveRecord $owner */ public function attach($owner) { $validator = new CSafeValidator(); $validator->attributes = array($this->attribute); $owner->getValidatorList()->add($validator); parent::attach($owner); }
public function run($action, $to, $id) { $to = CActiveRecord::model($this->getController()->CQtreeGreedView['modelClassName'])->findByPk((int) $to); $moved = CActiveRecord::model($this->getController()->CQtreeGreedView['modelClassName'])->findByPk((int) $id); if (!is_null($to) && !is_null($moved)) { try { switch ($action) { case 'child': $moved->moveAsLast($to); break; case 'before': if ($to->isRoot()) { $moved->moveAsRoot(); } else { $moved->moveBefore($to); } break; case 'after': if ($to->isRoot()) { $moved->moveAsRoot(); } else { $moved->moveAfter($to); } break; } } catch (Exception $e) { Yii::app()->user->setFlash('CQTeeGridView', $e->getMessage()); } } $this->getController()->redirect(array($this->getController()->CQtreeGreedView['adminAction'])); }
/** * fetch data */ protected function fetchData() { $criteria = $this->_criteria; $criteria->offset = $this->_offset; $criteria->limit = $this->batchSize; $this->_batch = $this->_model->findAll($criteria); $this->_offset += $this->batchSize; }
/** * 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); }
/** * Sets username fields of a model */ public static function usernameFieldsSet(CActiveRecord $model, $username) { if ($model->hasAttribute('updatedBy')) { $model->updatedBy = $username; } if ($model->hasAttribute('createdBy') && $model->isNewRecord) { $model->createdBy = $username; } }
/** * 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; }
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()); } }
/** * @param \CActiveRecord $model * * @return bool */ public function unSubscribe(\CActiveRecord $model) { try { if ($channel = $this->getChannel()) { return $channel->unSubscribe($model->getSubscriber()); } } catch (\CException $e) { } return false; }
/** * {@inheritDoc} * @see IExportFormat::format() */ public function format(CActiveRecord $record, array $data, array $templates = array()) { if (empty($data)) { throw new CDbException(Yii::t('yii', 'Can not generate multiple insert command with empty data set.')); } $templates = array_merge(array('main' => "INSERT INTO {{tableName}} ({{columnInsertNames}}) VALUES \n{{rowInsertValues}};\n", 'columnInsertValue' => '{{value}}', 'columnInsertValueGlue' => ', ', 'rowInsertValue' => '({{columnInsertValues}})', 'rowInsertValueGlue' => ",\n", 'columnInsertNameGlue' => ', '), $templates); $table = $record->tableSchema; if ($table === null) { throw new CDbException(Yii::t('yii', 'Table "{table}" does not exist.', array('{table}' => $record->tableName()))); } $tableName = $table->rawName; $columns = array(); foreach ($data as $rowData) { foreach ($rowData as $columnName => $columnValue) { if (!in_array($columnName, $columns, true)) { if ($table->getColumn($columnName) !== null) { $columns[] = $columnName; } } } } $columnInsertNames = array(); foreach ($columns as $name) { $columnInsertNames[$name] = $record->getDbConnection()->quoteColumnName($name); } $columnInsertNamesSqlPart = implode($templates['columnInsertNameGlue'], $columnInsertNames); $rowInsertValues = array(); foreach ($data as $rowData) { $columnInsertValues = array(); foreach ($columns as $columnName) { /* @var $column CDbColumnSchema */ $column = $table->getColumn($columnName); $columnValue = array_key_exists($columnName, $rowData) ? $rowData[$columnName] : new CDbException('NULL'); if ($columnValue instanceof CDbExpression) { $columnInsertValue = $columnValue->expression; // in reverse order to prevent precocious replacements on param values foreach (array_reverse($columnValue->params) as $columnValueParamName => $columnValueParam) { $secureColumnParamValue = $this->secureOutput($record->getDbConnection(), $columnValueParam); $columnInsertValue = strtr(':' . $columnValueParamName, $secureColumnParamValue, $columnInsertValue); } } else { $columnInsertValue = $column->typecast($columnValue); if ($columnInsertValue === '' && $column->allowNull) { $columnInsertValue = null; } $columnInsertValue = $this->secureOutput($record->getDbConnection(), $columnInsertValue); } $columnInsertValues[] = strtr($templates['columnInsertValue'], array('{{column}}' => $columnInsertNames[$columnName], '{{value}}' => $columnInsertValue)); } $rowInsertValues[] = strtr($templates['rowInsertValue'], array('{{tableName}}' => $tableName, '{{columnInsertNames}}' => $columnInsertNamesSqlPart, '{{columnInsertValues}}' => implode($templates['columnInsertValueGlue'], $columnInsertValues))); } $sql = strtr($templates['main'], array('{{tableName}}' => $tableName, '{{columnInsertNames}}' => $columnInsertNamesSqlPart, '{{rowInsertValues}}' => implode($templates['rowInsertValueGlue'], $rowInsertValues))); return $sql; }
/** * @param CActiveRecord $model * @param string $valueField defaults to primary key field * @param string $textField defaults to primary key field * @return array */ public static function listData($model, $valueField = '', $textField = '') { $pk = $model->metaData->tableSchema->primaryKey; if ($valueField === '') { $valueField = $pk; } if ($textField === '') { $textField = $valueField; } return CHtml::listData($model->findAll(array('select' => $valueField == $textField ? $valueField : $valueField . ',' . $textField)), $valueField, $textField); }
public function getValidParents() { $result = array(); $criteria = new CDbCriteria(); if (!$this->_model->getIsNewRecord()) { $criteria->addNotInCondition($this->getPK(), $this->getDescendantsIds($this->_model)); } foreach ($this->_model->findAll($criteria) as $model) { $result[$model->{$this->getPK()}] = $model->getCaption(); } return $result; }
/** * @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()); }
public function prepare($builder) { // override private `buildJoinWith()` if (!empty($this->joinWith)) { $this->buildJoinWith(); $this->joinWith = null; // clean it up to avoid issue https://github.com/yiisoft/yii2/issues/2687 } if (empty($this->from)) { $this->from = [$this->finder->tableName()]; } return parent::prepare($builder); }
/** * @param CActiveRecord $model * */ private static function Model2ArrayRec($model) { $data = $model->attributes; //Levantando relacionamentos $rels = $model->relations(); foreach ($rels as $relation => $params) { //Irá gerar um vetor com todos os relacionamentos if ($model->hasRelated($relation)) { $data[$relation] = self::relations2Array($model, $relation); } } return $data; }
/** * Renvoie une ligne à insérer dans le tableau 'attributes' d'un widget de type CDetailView, CGridView... * Le formatage varie selon le type de la colonne $column * @param CDbColumnSchema $column * @param CActiveRecord $templateRecord * @return string */ public static function getViewAttributesEntry(CDbColumnSchema $column, CActiveRecord $templateRecord) { switch ($column->dbType) { case 'date': $out = "{$column->name}:date:" . $templateRecord->getAttributeLabel($column->name); break; case 'datetime': $out = "{$column->name}:datetime:" . $templateRecord->getAttributeLabel($column->name); break; default: $out = $column->name; } return $out; }
/** * Displays the authorization assignments for an user. */ public function actionUser() { // Create the user model and attach the required behavior $userClass = $this->module->userClass; $model = CActiveRecord::model($userClass)->findByPk($_GET['id']); $this->_authorizer->attachUserBehavior($model); $assignedItems = $this->_authorizer->getAuthItems(null, $model->getId()); $assignments = array_keys($assignedItems); // Make sure we have items to be selected $assignSelectOptions = Rights::getAuthItemSelectOptions(null, $assignments); if ($assignSelectOptions !== array()) { $formModel = new AssignmentForm(); // Form is submitted and data is valid, redirect the user if (isset($_POST['AssignmentForm']) === true) { $formModel->attributes = $_POST['AssignmentForm']; if ($formModel->validate() === true) { // Update and redirect $this->_authorizer->authManager->assign($formModel->itemname, $model->getId()); $item = $this->_authorizer->authManager->getAuthItem($formModel->itemname); $item = $this->_authorizer->attachAuthItemBehavior($item); Yii::app()->user->setFlash($this->module->flashSuccessKey, Rights::t('core', 'Permission :name assigned.', array(':name' => $item->getNameText()))); $this->redirect(array('assignment/user', 'id' => $model->getId())); } } } else { $formModel = null; } // Create a data provider for listing the assignments $dataProvider = new RAuthItemDataProvider('assignments', array('userId' => $model->getId())); // Render the view $this->render('user', array('model' => $model, 'dataProvider' => $dataProvider, 'formModel' => $formModel, 'assignSelectOptions' => $assignSelectOptions)); }
/** * Returns the behaviors used for the model * * @return array * @see YdDressing::modelMap */ public function behaviors() { if (!empty(Yii::app()->dressing->modelMap[get_class($this)]['behaviors'])) { return Yii::app()->dressing->modelMap[get_class($this)]['behaviors']; } return parent::behaviors(); }
public function beforeSave() { if ($this->isNewRecord && !$this->time) { $this->time = new CDbExpression('UTC_TIMESTAMP()'); } return parent::beforeSave(); }
public function validateModel($attribute, $params) { if ($this->hasErrors('model')) { return; } $class = @Yii::import($this->model, true); if (!is_string($class) || !$this->classExists($class)) { $this->addError('model', "Class '{$this->model}' does not exist or has syntax error."); } else { if (!is_subclass_of($class, 'CActiveRecord')) { $this->addError('model', "'{$this->model}' must extend from CActiveRecord."); } else { $table = CActiveRecord::model($class)->tableSchema; if ($table->primaryKey === null) { $this->addError('model', "Table '{$table->name}' does not have a primary key."); } else { if (is_array($table->primaryKey)) { $this->addError('model', "Table '{$table->name}' has a composite primary key which is not supported by crud generator."); } else { $this->_modelClass = $class; $this->_table = $table; } } } } }
public function setUp() { if (!extension_loaded('pdo') || !extension_loaded('pdo_pgsql')) { $this->markTestSkipped('PDO and PostgreSQL extensions are required.'); } $this->db = new CDbConnection('pgsql:host=127.0.0.1;dbname=yii', 'test', 'test'); try { $this->db->active = true; } catch (Exception $e) { $schemaFile = realpath(dirname(__FILE__) . '/../data/postgres.sql'); $this->markTestSkipped("Please read {$schemaFile} for details on setting up the test environment for PostgreSQL test case."); } try { $this->db->createCommand('DROP SCHEMA test CASCADE')->execute(); } catch (Exception $e) { } try { $this->db->createCommand('DROP TABLE yii_types CASCADE')->execute(); } catch (Exception $e) { } $sqls = file_get_contents(dirname(__FILE__) . '/../data/postgres.sql'); foreach (explode(';', $sqls) as $sql) { if (trim($sql) !== '') { $this->db->createCommand($sql)->execute(); } } $this->db->active = false; $config = array('basePath' => dirname(__FILE__), 'components' => array('db' => array('class' => 'system.db.CDbConnection', 'connectionString' => 'pgsql:host=127.0.0.1;dbname=yii', 'username' => 'test', 'password' => 'test'))); $app = new TestApplication($config); $app->db->active = true; CActiveRecord::$db = $this->db = $app->db; }
public function beforeSave() { parent::beforeSave(); $picture = CUploadedFile::getInstance($this, 'image'); if ($picture) { $imagename = $picture->getTempName(); $image = Yii::app()->image->load($imagename); if ($image) { if ($this->avatar) { unlink($_SERVER['DOCUMENT_ROOT'] . $this->avatar_folder . '/' . $this->avatar); } if ($image->width >= $image->height) { $image->resize(20000, 93)->rotate(0)->quality(90)->sharpen(20); } else { $image->resize(93, 20000)->rotate(0)->quality(90)->sharpen(20); } $image->crop(93, 93); $file_name = rand() . '.' . $picture->extensionName; $savename = $_SERVER['DOCUMENT_ROOT'] . $this->avatar_folder . '/' . $file_name; $image->save($savename); $this->avatar = $file_name; } } return true; }
function __get($name) { if ($name == 'description') { return $this->description(); } return parent::__get($name); }
/** * {@inheritdoc} * * @param array $fixtures fixtures to be loaded. The array keys are fixture * names, and the array values are either AR class names or table names. If * table names, they must begin with a colon character (e.g. 'Post' means * an AR class, while ':Post' means a table name). * * @return void * @since 0.1.0 */ public function load($fixtures) { //$schema = $this->getDbConnection()->getSchema(); //$schema->checkIntegrity(false); $this->_rows = array(); $this->_records = array(); foreach ($fixtures as $fixtureName => $tableName) { if ($tableName[0] === ':') { $tableName = substr($tableName, 1); unset($modelClass); } else { $modelClass = \Yii::import($tableName, true); $tableName = CActiveRecord::model($modelClass)->tableName(); } if (($prefix = $this->getDbConnection()->tablePrefix) !== null) { $tableName = preg_replace('/{{(.*?)}}/', $prefix . '\\1', $tableName); } $this->resetTable($tableName); $rows = $this->loadFixture($tableName); if (is_array($rows) && is_string($fixtureName)) { $this->_rows[$fixtureName] = $rows; if (isset($modelClass)) { foreach (array_keys($rows) as $alias) { $this->_records[$fixtureName][$alias] = $modelClass; } } } } //$schema->checkIntegrity(true); }
protected function beforeSave() { if ($this->pickup_date != '') { $this->pickup_date = date('Y-m-d', strtotime($this->pickup_date)); } return parent::beforeSave(); }