protected function validateAttribute($object, $attribute) { $object = ActiveRecord::model($object->model_id)->findByPk($object->object_id); if (!$object) { $this->addError($object, $attribute, "Объекта с моделью '{$object->model_id}' и ID '{$object->object_id}' не существует!"); } }
public function run() { Yii::import('application.models.*'); $path = Yii::app()->request->getParam('path'); $id = Yii::app()->request->getParam('id'); $widget = Yii::app()->request->getParam('widget'); $data = AdminWidget::getWidgetDataByPath($widget); $modelName = $data['model']; $tableName = ActiveRecord::model($modelName)->tableName(); $d = Yii::app()->db->createCommand('select MAX(sort),MIN(sort) FROM ' . $tableName . ' where active = 1')->queryRow(false); $max = intval($d[0]); $min = intval($d[1]); $pk = ActiveRecord::model($modelName)->tableSchema->primaryKey; $model = ActiveRecord::model($modelName)->findByPk($id); if ($model->sort != $max && $path == 'down' || $model->sort != $min && $path == 'up') { if ($path == 'down') { $s = $model->sort + 1; $c = Yii::app()->db->createCommand("update {$tableName} set sort = sort-1 where sort = {$s}")->execute(); $r = Yii::app()->db->createCommand("update {$tableName} set sort = sort+1 where {$pk} = {$id}")->execute(); } else { $s = $model->sort - 1; $c = Yii::app()->db->createCommand("update {$tableName} set sort = sort+1 where sort = {$s}")->execute(); $r = Yii::app()->db->createCommand("update {$tableName} set sort = sort-1 where {$pk} = {$id}")->execute(); } } }
/** * Creates a new pagination object * * @param $model A string containg the name of model to be used or the model itself (can use named scopes) * @param $per_page The number of records per pege to display * @param $query Query data to be passed when quering ActiveRecord * @return ArPagination */ public function __construct($model, $per_page = 10, $query = array()) { $this->model = is_string($model) ? ActiveRecord::model($model) : $model; $this->query = $query; $this->per_page = $per_page; $this->config = $this->default_config(); }
public static function getString($model_id, $object_id) { $model = ActiveRecord::model($model_id)->findByPk($object_id); if ($model) { $result = CHtml::listData($model->tags, 'id', 'name'); return implode(', ', $result); } return ''; }
public function findAllAttaches() { $model = $this->getOwner(); $object_id = $model->isNewRecord ? $this->_tmpPrefix() : $model->id; return ActiveRecord::model(get_class($this->getOwner()))->findAllByAttributes(array( 'object_id' => $object_id, 'model_id' => get_class($model) )); }
public function __construct($local_model, $foreign_model, $options = array()) { $this->local_model = $local_model; $this->foreign_model = class_exists($foreign_model) ? ActiveRecord::model($foreign_model) : $foreign_model; $this->options = $options; $this->_data = null; $this->_newdata = null; $this->_changed = false; }
protected function validateAttribute($object, $attribute) { $model = ActiveRecord::model($object->model_id)->findByPk($object->object_id); if (!$model) { $this->addError($object, $attribute, "Объекта с моделью '{$object->model_id}' и ID '{$object->object_id}' не существует!"); } else { if (property_exists($object, 'target_model')) { $object->target_model = $model; } } }
/** * @param int|string $id * @param bool $throw * @return ActiveRecord * @throws \CHttpException */ public final function loadModel($id, $throw = true) { /** * @var ActiveRecord $model */ $model = ActiveRecord::model($this->modelName); $model = $model->findByPk($id); if ($throw && null === $model) { throw new \CHttpException(404, 'The requested page does not exist.'); } return $model; }
protected function validateAttribute($object, $attribute) { if (Yii::app()->user->isGuest) { return; } $model = ActiveRecord::model($object->model_id)->findByPk($object->object_id); if (!$model) { return; } if ($model->user_id == Yii::app()->user->id) { $this->addError($object, 'object_id', "Автору объекта запрещено!"); } }
public function getObject() { $models = AppManager::getModels(); if (!isset($models[$this->model_id])) { return; } $object = ActiveRecord::model($this->model_id)->findByPk($this->object_id); if ($object) { return $object; } else { return '<span style="color:red">не существует</span>'; } }
public function actionCreateTableField($model) { $model = ActiveRecord::model($model); $table = $model->tableName(); $meta = $model->meta(); if (!isset($meta['language'])) { $sql = "ALTER TABLE `{$table}`\r\n ADD `language` char(2) DEFAULT 'ru' COMMENT 'Язык' AFTER `id`"; Yii::app()->db->createCommand($sql)->execute(); $sql = 'ALTER TABLE `{$table}` ADD CONSTRAINT `{$table}_language_fk` FOREIGN KEY (`language`) REFERENCES `languages` (`id`) ON DELETE CASCADE ON UPDATE CASCADE'; Yii::app()->db->createCommand($sql)->execute(); } $this->redirect('/'); }
public function run($id) { $model = $this->model ? ActiveRecord::model($this->model)->findByPk($id) : $this->controller->loadModel($id); $model->scenario = 'update'; $this->controller->performAjaxValidation($model); $attr = $_POST['attr']; if (isset($_POST[$attr]) && in_array($attr, $this->attributes)) { $model->{$attr} = trim(strip_tags($_POST[$attr])); if ($model->save(false)) { echo $model->{$attr}; } } }
/** * @param $model - profile model * @param $field - profile fields model item * @return string */ public function viewAttribute($model, $field) { $relation = $model->relations(); if ($this->params['relationName'] && isset($relation[$this->params['relationName']])) { $m = $model->__get($this->params['relationName']); } else { $m = ActiveRecord::model($this->params['modelName'])->findByPk($model->getAttribute($field->varname)); } if ($m) { return $this->params['optionName'] ? $m->getAttribute($this->params['optionName']) : $m->id; } return $this->params['emptyField']; }
public function refresh() { if (isset($this->options['polymorphic']) && $this->options['polymorphic'] == true) { $as = Ra_StringHelper::underscore($this->foreign_model); $id_field = $as . "_id"; $type_field = $as . "_type"; $value = $this->local_model->{$id_field}; return ActiveRecord::model($this->local_model->{$type_field})->find($value); } else { $foreign_field = $this->get_foreign_field($this->foreign_model); $foreign_key_field = $this->foreign_model->primary_key(); $data = $this->foreign_model->find($this->local_model->{$foreign_field}); return $data; } }
function getObjectUpdateUrl($object_id, $model) { try { if (!is_numeric($object_id) || !method_exists($model, 'updateUrl')) { return; } $object = ActiveRecord::model($model)->findByPk($object_id); if (!$object) { return; } return CHtml::link('перейти', $object->updateUrl()); } catch (Exception $e) { return 'Удален'; } }
public function __construct($response, $config = array()) { $this->response = $response; $matches = array(); foreach ($this->response['matches'] as $id => $data) { $match = new stdClass(); foreach ($data['attrs'] as $key => $value) { $match->{$key} = $value; } $match->id = $id; $match->model = ActiveRecord::model($match->model_id)->findByPk($match->object_id); $match->_weight = $data['weight']; $matches[$id] = $match; } parent::__construct($matches, $config); }
public function has_admin() { $admin = true; $user_submenus = $this->individual_submenus(); $submenus = ActiveRecord::model('Submenu')->all(); $menu_submenus = array(); foreach ($submenus as $submenu) { $menu_submenus[] = (int) $submenu->id; } foreach ($menu_submenus as $submenu_id) { if (!in_array($submenu_id, $user_submenus)) { $admin = false; } } return $admin; }
protected function preFilter($filterChain) { /** @var $controller Controller */ $controller = $filterChain->controller; if ($this instanceof AdminController) { return true; } if ($val = Yii::app()->request->getParam($this->getParam)) { $class = $controller->getModelClass(); if ($class) { $model = ActiveRecord::model($class)->findByAttributes(array($this->findAttribute => $val)); if ($model) { $controller->setMetaTags($model); } } } return true; }
public static function getCode($model_class) { $model = ActiveRecord::model($model_class); $meta = $model->meta(); $params = array('class' => $model_class, 'upload' => (bool) $model->uploadFiles()); $elements = array(); foreach ($meta as $data) { $attr = $data['Field']; if (in_array($attr, array('id', 'date_create', 'date_update'))) { continue; } if (in_array($attr, Model::$file_attributes)) { $elements[$attr] = array('type' => 'file'); } else { if (in_array($attr, array('password', 'password_c'))) { $elements[$attr] = array('type' => 'password'); } else { if (substr($attr, 0, 3) == 'is_') { $elements[$attr] = array('type' => 'checkbox'); } else { if (preg_match('|varchar\\(([0-9]+)\\)|', $data['Type'], $length)) { $length = $length[1]; if ($length <= 55) { $elements[$attr] = array('type' => 'text'); } else { $elements[$attr] = array('type' => 'textarea'); } } else { if (in_array($data['Type'], array('date', 'datetime'))) { $elements[$attr] = array('type' => 'date'); } else { if (preg_match('|enum\\(.*?\\)|', $data['Type'])) { $elements[$attr] = array('type' => 'dropdownlist', 'items' => $model_class . '::$' . $attr . '_options', 'empty' => 'не выбрано'); } } } } } } } $params['elements'] = $elements; return Yii::app()->controller->renderPartial('codegen.views.templates.crud.forms.Form', $params, true); }
public function run() { if ($this->id) { $model = ActiveRecord::model($this->modelName)->findByPk($this->id); } else { $model = new $this->modelName(); } if (!in_array('CModel', class_parents($model))) { throw new CException('Not correct model class'); } if (Yii::app()->request->isPostRequest) { if ($model->delete()) { Yii::app()->user->setFlash("OPERATION_RESULT", "Удалено успешно"); } else { Yii::app()->user->setFlash("OPERATION_RESULT", "Не сохранено"); } } else { } }
public function run() { if ($this->id) { $model = ActiveRecord::model($this->modelName)->findByPk($this->id); } else { $model = new $this->modelName(); } if (!in_array('CModel', class_parents($model))) { throw new CException('Not correct model class'); } if (isset($_POST[$this->modelName])) { $model->attributes = $_POST[$this->modelName]; if ($model->save()) { Yii::app()->user->setFlash("OPERATION_RESULT", "Сохранено успешно"); $this->getController()->redirect($this->returnUrl ? $this->returnUrl : Yii::app()->user->getReturnUrl($this->returnUrl ? $this->returnUrl : '/admin')); } else { Yii::app()->user->setFlash("OPERATION_RESULT", "Не сохранено"); } } $this->render('model', array('model' => $model, 'buttonType' => "save", 'attributes' => $model->getFieldSettingsForAdminPanel())); }
private function _save($options) { $model = ActiveRecord::model($options['model'])->findByPk($options['id']); //may be you will be need set some attributes before update if (isset($options['attributes'])) { $model->attributes = $options['attributes']; } $attribute = $options['attribute']; $model->{$attribute} = $options['value']; if ($model->saveAttributes(array($attribute))) { if (isset($options['unlink_file'])) { $file = Yii::getPathOfAlias('webroot') . '/' . $options['unlink_file']; if (is_file($file) && FileSystemHelper::isAllowForUnlink($file)) { FileSystemHelper::deleteFileWithSimilarNames(pathinfo($file, PATHINFO_DIRNAME), pathinfo($file, PATHINFO_BASENAME)); } } echo $model->{$attribute}; } else { echo $model->getError($attribute); } }
public function actionColumnsManage($model_id, $widget_id) { $model = ActiveRecord::model($model_id); if (isset($_POST['columns'])) { file_put_contents(WidgetManager::getVisibleColumnsFilePath($model_id, $widget_id), serialize(explode(',', $_POST['columns']))); if (isset($_GET['redirect'])) { $this->redirect(base64_decode($_GET['redirect'])); } } $visible_columns = WidgetManager::getVisibleColumns($model_id, $widget_id); $hidden_columns = array(); $attributes = array_keys($model->attributeLabels()); $visible_columns = array_intersect($visible_columns, $attributes); foreach ($attributes as $attribute) { if ($attribute == 'captcha') { continue; } if (in_array($attribute, $visible_columns)) { continue; } $hidden_columns[] = $attribute; } $this->render('columnsManage', array('visible_columns' => $visible_columns, 'hidden_columns' => $hidden_columns, 'model' => $model)); }
/** * Returns the static model of the specified AR class. * Please note that you should have this exact method in all your CActiveRecord descendants! * @param string $className active record class name. * @return Usuarios the static model class */ public static function model($className = __CLASS__) { return parent::model($className); }
public function get_site_users_count() { return ActiveRecord::model('SiteUser')->count(array('conditions' => 'state_id = ' . $this->id)); }
public static function validates_match_post_of($object, $field, $post_var, $err) { $password = $object->{$field}; $pk = $object->primary_key(); $obj_test = ActiveRecord::model(get_class($object))->find($object->{$pk}); if ($obj_test && $obj_test->password != $object->password) { $confirmation = $_POST[$post_var]; if ($password != md5($confirmation)) { $object->add_error($field, $err ? $err : sprintf(self::$validations_messages['invalid_match_post_of'], $field, $value)); return false; } } else { $confirmation = @$_POST[$post_var]; if ($password != md5($confirmation)) { $object->add_error($field, $err ? $err : sprintf(self::$validations_messages['invalid_match_post_of'], $field, $value)); return false; } } return true; }
/** * Возвращает модель по атрибуту и удовлетворяющую скоупам, * или выбрасывает 404 * * @param string $class имя класса модели * @param int|string|array $valueOrArray значение атрибута * @param array $scopes массив скоупов * * @return CActiveRecord */ public function loadModel($valueOrArray, $scopes = array()) { $model = ActiveRecord::model($this->getModelClass()); foreach ($scopes as $scope) { $model->$scope(); } if (is_array($valueOrArray)) { return $model->throw404IfNull()->findByAttributes($valueOrArray); } else { return $model->throw404IfNull()->findByPk($valueOrArray); } }
public function image_cache($model, $field, $id = null, $configuration = array(), $user_vars = array()) { $configuration = array_merge(array('width' => 100, 'height' => 100, 'mode' => 1, 'format' => 'jpg', 'path_format' => '#cache/#model/#field/#id.#width.#height.#mode.#format', 'default' => ''), $configuration); $vars = array_merge(array('cache' => RA_CACHE_PATH, 'model' => $model, 'field' => $field, 'id' => $id, 'width' => $configuration['width'], 'height' => $configuration['height'], 'mode' => $configuration['mode'], 'format' => $configuration['format']), $user_vars); $path = Ra_StringHelper::simple_template($configuration['path_format'], $vars); $object = is_a($model, 'ActiveRecord') ? $model : ActiveRecord::model($model)->find($id); if ($object->{$field}) { if (file_exists($path) && file_exists($object->{$field}) && filemtime($object->{$field}) > filemtime($path)) { unlink($path); } if (!file_exists($path)) { if ($object->{$field}) { Ra_DirectoryHelper::mkdir($path, true); $image = new Ra_Image($object->{$field}); $image->resize($configuration['width'], $configuration['height'], $configuration['mode']); $image->save($path); } } } else { $this->redirect_to('public/' . $configuration['default']); } return file_get_contents($path); }
public static function getModels($params = array()) { $result = array(); $modules_dirs = scandir(MODULES_PATH); foreach ($modules_dirs as $module_dir) { if ($module_dir[0] == '.') { continue; } $module_class = ucfirst($module_dir) . 'Module'; if (array_key_exists('active', $params)) { $active_attr = new ReflectionProperty($module_class, 'active'); if ($active_attr->getValue() !== $params['active']) { continue; } } $models_dir = MODULES_PATH . $module_dir . '/models'; if (!file_exists($models_dir)) { continue; } $models_files = scandir($models_dir); foreach ($models_files as $model_file) { if ($model_file[0] == '.') { continue; } $model_class = str_replace('.php', null, $model_file); $class = new ReflectionClass($model_class); if ($class->isSubclassOf('ActiveRecord')) { $model = ActiveRecord::model($model_class); } else { continue; } if (isset($params['meta_tags'])) { $behaviors = $model->behaviors(); $behaviors = ArrayHelper::extract($behaviors, 'class'); if (!in_array('application.components.activeRecordBehaviors.MetaTagBehavior', $behaviors)) { continue; } } $result[$model_class] = $model->name(); } } return $result; }
private function add_joins(&$sql, $joins) { if (is_array($joins)) { $cur_table = $this->table(); $cur_key = $this->primary_key(); $cur_fk = strtolower(get_class($this)) . '_id'; foreach ($joins as $join) { $model = ActiveRecord::model($join); $join_table = $model->table(); $join_key = $model->primary_key(); $join_fk = strtolower(get_class($model)) . '_id'; $sql .= "INNER JOIN `{$join_table}` ON `{$join_table}`.`{$cur_fk}` = `{$cur_table}`.`{$cur_key}` "; } } elseif (is_string($joins)) { $sql .= $joins . " "; } }