public static function tableOrder($field, CModel $model = null, $manualSort = false) { if (is_null($model)) { return ""; } $labels = CCoreObjectsManager::getAttributeLabels($model); $columnLabels = CCoreObjectsManager::getAttributeTableLabels($model); if (array_key_exists($field, $columnLabels)) { $label = $columnLabels[$field]; } elseif (array_key_exists($field, $labels)) { $label = $labels[$field]; } else { $label = $field; } $exclude = array('order', 'direction'); foreach (CRequest::getGlobalRequestVariables()->getItems() as $key => $value) { if (!in_array($key, $exclude)) { if (is_scalar($value)) { $actions[] = $key . "=" . $value; } } } /** * Позволяем сортировать только если поле есть в модели */ $showLink = $manualSort; if (is_a($model, "CActiveModel")) { if ($model->getDbTableFields()->hasElement($field)) { $showLink = true; } } $actions[] = "order=" . $field; if (CRequest::getString("order") == $field) { if (CRequest::getString("direction") == "") { $actions[] = "direction=asc"; } elseif (CRequest::getString("direction") == "asc") { $actions[] = "direction=desc"; } elseif (CRequest::getString("direction") == "desc") { $actions[] = "direction=asc"; } } else { $actions[] = "direction=desc"; } if ($showLink) { $label = '<a href="?' . implode($actions, "&") . '">' . $label . '</a>'; } echo $label; }
/** * Получение данных модели по идентификатору */ private function actionJSONGet() { // получим название класса модели, которую надо пользователю $modelClass = CRequest::getString("model"); // идентификатор $id = CRequest::getInt("id"); // создадим объект, посмотрим, в какой таблице он весь живет /** * @var $model CActiveModel */ $model = new $modelClass(); // проверим, может не реализует нужный интерфейс if (!is_a($model, "IJSONSerializable")) { throw new Exception("Класс " . $modelClass . " не реализует интерфейс IJSONSerializable"); } $modelTable = $model->getRecord()->getTable(); // получим из этой таблицы объект $ar = CActiveRecordProvider::getById($modelTable, $id); if (is_null($ar)) { echo json_encode(null); return; } // создадим новый объект указанного типа /** * @var $model IJSONSerializable */ $model = new $modelClass($ar); // получим json объект модели $jsonObj = $model->toJsonObject(); // добавим к json-объекту перевод $jsonObj->_translation = CCoreObjectsManager::getAttributeLabels($model); // сразу добавим штатную валидацию // может, чуть позже, пока нет echo json_encode($jsonObj); }
/** * Функция валидации данных модели * * @return bool */ public function validate() { /** * Валидация полей модели */ $rules = CCoreObjectsManager::getFieldValidators($this); $labels = CCoreObjectsManager::getAttributeLabels($this); foreach ($rules as $field => $validators) { try { foreach ($validators as $validator) { if (is_object($validator)) { /** * Это новая система валидаторов */ if (!$validator->run($this->{$field})) { $error = str_replace("%name%", $labels[$field], $validator->getError()); $this->getValidationErrors()->add($field, $error); } } elseif (is_string($validator)) { /** * Это старая система валидаторов */ if ($validator == "required") { if ($this->{$field} == "") { $error = str_replace("%name%", $labels[$field], ERROR_FIELD_REQUIRED); $this->getValidationErrors()->add($field, $error); } } elseif ($validator == "numeric") { if (!is_numeric($this->{$field})) { $error = str_replace("%name%", $labels[$field], ERROR_FIELD_NUMERIC); $this->getValidationErrors()->add($field, $error); } } elseif ($validator == "selected") { if (is_a($this->{$field}, "CArrayList")) { if ($this->{$field}->getCount() == 0) { $error = str_replace("%name%", $labels[$field], ERROR_FIELD_SELECTED); $this->getValidationErrors()->add($field, $error); } } else { if ($this->{$field} == 0) { $error = str_replace("%name%", $labels[$field], ERROR_FIELD_SELECTED); $this->getValidationErrors()->add($field, $error); } } } elseif ($validator == "checkdate") { if ($this->{$field} != "") { $dateValue = $this->{$field}; $error = str_replace("%name%", $labels[$field], ERROR_FIELD_NOT_A_DATE); if (strtotime($dateValue) === false) { $this->getValidationErrors()->add($field, $error); } else { $dateArray = explode(".", $dateValue); if (!checkdate($dateArray[1], $dateArray[0], $dateArray[2])) { $this->getValidationErrors()->add($field, $error); } } } } } } } catch (Exception $e) { die("Error on field " . $field . " => " . $e->getMessage() . " on line " . $e->getLine()); } } $this->validateModel(VALIDATION_EVENT_UPDATE); return $this->getValidationErrors()->getCount() == 0; }