PHP Class yii\base\ Model Code Examples

PHP yii\base\Model - 30 examples found. These are the top rated real world PHP examples of class yii\base\Model extracted from open source projects. You can rate examples to help us improve the quality of examples
Model implements the following commonly used features: - attribute declaration: by default, every public class member is considered as a model attribute - attribute labels: each attribute may be associated with a label for display purpose - massive attribute assignment - scenario-based validation Model also raises the following events when performing data validation: - [[EVENT_BEFORE_VALIDATE]]: an event raised at the beginning of Model::validate - [[EVENT_AFTER_VALIDATE]]: an event raised at the end of Model::validate You may directly use Model to store model data, or extend it with customization. For more details and usage information on Model, see the guide article on models.
Since: 2.0
Author: Qiang Xue (qiang.xue@gmail.com)
Inheritance: extends Component, implements IteratorAggregat\IteratorAggregate, implements ArrayAcces\ArrayAccess, implements yii\base\Arrayable, use trait ArrayableTrait
 /**
  * @inheritdoc
  */
 public function init()
 {
     parent::init();
     if (!$this->header) {
         $this->header = "<h2>" . Inflector::camel2words($this->model->formName()) . " change log:</h2>";
     }
 }
Example #2
0
 public function getHotlinkTo(Model $model, $action = null, $options = [])
 {
     if (!ArrayHelper::isIn($this->className(), ArrayHelper::getColumn($model->behaviors(), 'class'))) {
         throw new InvalidRouteException('The "LinkableBehavior" is not attached to the specified model');
     }
     return $this->getHotlink(strtr('{route}/{action}', ['{route}' => $model->route, '{action}' => $action ?? $model->defaultAction]), $model->linkableParams, $options);
 }
Example #3
0
 /**
  * Retrieves grid columns configuration using the modelClass.
  * @param Model $model
  * @param array $fields
  * @return array grid columns
  */
 public function getIndexGridColumns($model, $fields)
 {
     $id = Yii::$app->request->getQueryParam('id');
     $relationName = Yii::$app->request->getQueryParam('relation');
     $multiple = Yii::$app->request->getQueryParam('multiple', 'true') === 'true';
     foreach ($fields as $key => $field) {
         if ((is_array($field) || !is_string($field) && is_callable($field)) && $key === $relationName || $field === $relationName) {
             unset($fields[$key]);
         }
     }
     return array_merge([['class' => 'yii\\grid\\CheckboxColumn', 'multiple' => $multiple, 'headerOptions' => ['class' => 'column-serial'], 'checkboxOptions' => function ($model, $key, $index, $column) use($id, $relationName) {
         /** @var \yii\db\ActiveRecord $model */
         $options = ['value' => is_array($key) ? json_encode($key, JSON_UNESCAPED_SLASHES | JSON_UNESCAPED_UNICODE) : $key];
         if (empty($relationName) || $model->{$relationName} === null || trim($id) === '') {
             return $options;
         }
         $relation = $model->getRelation($relationName);
         if ($relation->multiple) {
             /** @var \yii\db\ActiveRecord $relationClass */
             $relationClass = $relation->modelClass;
             if (Action::importKey($relationClass::primaryKey(), $id) === $model->getAttributes(array_keys($relation->link))) {
                 $options['checked'] = true;
                 $options['disabled'] = true;
             }
         } elseif (Action::exportKey($relation->one()->getPrimaryKey()) === $id) {
             $options['checked'] = true;
             $options['disabled'] = true;
         }
         return $options;
     }], ['class' => 'yii\\grid\\SerialColumn', 'headerOptions' => ['class' => 'column-serial']]], self::getGridColumns($model, $fields));
 }
 /**
  * Returns source attribute
  *
  * @param string $attribute
  * @throws InvalidValueException
  * @return mixed
  */
 public function getAttribute($attribute)
 {
     if ($this->source->canGetProperty($attribute)) {
         return $this->source->{$attribute};
     }
     throw new InvalidValueException('Unknown attribute: ' . $attribute);
 }
Example #5
0
 /**
  * Performs ajax validation.
  *
  * @param \yii\base\Model $model
  *
  * @throws \yii\base\ExitException
  */
 protected function performValidationModel(Model $model)
 {
     if ($model->load(Yii::$app->request->post())) {
         return ActiveForm::validate($model);
     }
     return;
 }
Example #6
0
 /**
  * Populates the model with input data.
  * @param Model $model model instance.
  * @param array $data the data array to load, typically `$_POST` or `$_GET`.
  * @return boolean whether expected forms are found in `$data`.
  */
 protected function load($model, $data)
 {
     /* @var $this Action */
     $event = new ActionEvent($this, ['model' => $model, 'result' => $model->load($data)]);
     $this->trigger('afterDataLoad', $event);
     return $event->result;
 }
Example #7
0
 /**
  * server validatiom for unique zip_code
  * @param \yii\base\Model $model
  * @param string $attribute
  */
 public function validateAttribute($model, $attribute)
 {
     $value = $model->{$attribute};
     if (!Locations::find()->where(['zip_code' => $value])->exists()) {
         $model->addError($attribute, $this->message);
     }
 }
Example #8
0
 /**
  * Performs ajax validation.
  *
  * @param Model $model
  *
  * @throws \yii\base\ExitException
  */
 protected function performAjaxValidation(Model $model)
 {
     if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
         Yii::$app->response->format = Response::FORMAT_JSON;
         Yii::$app->response->content = ActiveForm::validate($model);
         Yii::$app->end();
     }
 }
Example #9
0
 /**
  * Performs ajax validation.
  * @param Model $model
  * @throws \yii\base\ExitException
  */
 protected function performAjaxValidation(Model $model)
 {
     if (\Yii::$app->request->isAjax && $model->load(\Yii::$app->request->post())) {
         \Yii::$app->response->format = Response::FORMAT_JSON;
         echo json_encode(ActiveForm::validate($model));
         \Yii::$app->end();
     }
 }
 /**
  * Applies the required formatting and params to messages.
  * @param Model $model
  * @param string $attribute
  * @return array Prepared messages
  */
 public function prepareMessages($model, $attribute)
 {
     $params = array_merge($this->messageParams(), ['attribute' => $model->getAttributeLabel($attribute)]);
     $messages = [];
     foreach ($this->messages() as $name => $message) {
         $messages[$name] = Yii::$app->getI18n()->format($message, $params, Yii::$app->language);
     }
     return $messages;
 }
Example #11
0
 /**
  * Берет значения из POST и возвраает знаяения для добавления в БД
  *
  * @param array           $field
  * @param \yii\base\Model $model
  *
  * @return array
  */
 public static function onLoad($field, $model)
 {
     $fieldName = $field[BaseForm::POS_DB_NAME];
     $value = ArrayHelper::getValue(\Yii::$app->request->post(), $model->formName() . '.' . $fieldName, false);
     if ($value) {
         $value = true;
     }
     $model->{$fieldName} = $value;
 }
 /**
  * @inheritdoc
  */
 public function run()
 {
     Asset::register($this->view);
     $inputId = Html::getInputId($this->model, $this->attribute);
     $field = $this->render('_field', ['fieldClass' => 'field-' . $inputId, 'inputId' => $inputId, 'inputName' => Html::getInputName($this->model, $this->attribute) . '[]', 'inputLabel' => $this->model->getAttributeLabel($this->attribute)]);
     $options = Json::htmlEncode(['field' => $field, 'firstAddTogglerText' => 'добавить свою категорию', 'addTogglerText' => 'добавить ещё', 'values' => $this->model->{$this->attribute}]);
     $this->view->registerJs('jQuery("#' . $this->id . '").kategoriiSlushatelejInputFields(' . $options . ');');
     return Html::tag('div', $this->renderFirstToggler(), ['id' => $this->id, 'class' => 'kategorii-slushatelej-input-fields']);
 }
Example #13
0
 public static function modelErrors(Model $model, $message = null, $category = 'application')
 {
     if (!is_null($message)) {
         static::error($message, $category);
     }
     if ($model->hasErrors()) {
         static::error(['class' => get_class($model), 'attributes' => $model->getAttributes(), 'errors' => $model->getErrors()], $category);
     }
 }
Example #14
0
 /**
  * Serializes the validation errors in a model.
  * @param Model $model
  * @return array the array representation of the errors
  */
 protected function serializeModelErrors($model)
 {
     Yii::$app->response->setStatusCode(422, 'Data Validation Failed.');
     $result = [];
     foreach ($model->getFirstErrors() as $name => $message) {
         $result[] = ['field' => $name, 'message' => $message];
     }
     return $result;
 }
Example #15
0
 public static function checkRequiredParams($params, $required_params)
 {
     $missing_parameters = self::allTheRequiredParametersAre($params, $required_params);
     $model = new Model();
     if ($missing_parameters) {
         $model->addError("this parameters are missing ", $error = implode(", ", $missing_parameters));
     }
     return $model;
 }
Example #16
0
 /**
  * @return array
  */
 public function getErrors()
 {
     if (empty($this->_errors)) {
         foreach ($this->_model->getFirstErrors() as $name => $message) {
             $this->_errors[] = ['field' => $name, 'message' => $message];
         }
     }
     return $this->_errors;
 }
 /**
  * @inheritdoc
  */
 public function set(Model $model)
 {
     if (Yii::$app->user->getIsGuest()) {
         return;
     }
     $data = $model->toArray();
     $this->getStorage()->setBounded('theme', $data);
     $this->setToCache($data);
 }
Example #18
0
 /**
  * @param \yii\base\Model $model
  *
  * @return string
  */
 protected function getCategory(Model $model)
 {
     if (!$model->isNewRecord) {
         $id = $model->id;
         $category = self::className() . ':' . $model->formName() . '-' . $id;
     } else {
         $category = self::className() . ':' . $model->formName();
     }
     return $category;
 }
Example #19
0
 /**
  * Extracts Model errors from array and puts them into string
  * @param Model $model
  * @param boolean $html
  * @return string
  */
 public static function errorsToString($model, $html = true)
 {
     $result = '';
     $delimiter = $html ? "<br/>\n" : "\n";
     foreach ($model->errors as $attribute => $error) {
         $errors = implode(', ', $error);
         $result .= $model->getAttributeLabel($attribute) . ": {$errors}{$delimiter}";
     }
     return $result;
 }
 /**
  * @param Model $model
  * @param string $message
  * @param int $code
  * @param Exception $previous
  */
 public function __construct(Model $model, $message = null, $code = 0, Exception $previous = null)
 {
     $this->model = $model;
     if (is_null($message) && $model->hasErrors()) {
         $message = implode(' ', array_map(function ($errors) {
             return implode(' ', $errors);
         }, $model->getErrors()));
     }
     parent::__construct($message, $code, $previous);
 }
Example #21
0
 /**
  * @param Model|ActiveRecordInterface $model
  * @return array list of variation models in format: behaviorName => Model[]
  */
 private function findRoleModels($model)
 {
     $roleModels = [];
     foreach ($model->getBehaviors() as $name => $behavior) {
         if (empty($this->roleNames) && $behavior instanceof \yii2tech\ar\role\RoleBehavior || in_array($name, $this->roleNames)) {
             $roleModels[$name] = $behavior->getRoleRelationModel();
         }
     }
     return $roleModels;
 }
Example #22
0
 protected function performAjaxValidation(Model $model)
 {
     $isAjaxRequest = \Yii::$app->request->isAjax();
     $postData = \Yii::$app->request->post();
     if ($isAjaxRequest && $model->load($postData)) {
         Yii::$app->response->format = Response::FORMAT_JSON;
         echo json_encode(ActiveForm::validate($model));
         Yii::$app->end();
     }
 }
 /**
  * @param \yii\base\Model $model
  *
  * @return string
  */
 public function getModelDirectory(Model $model)
 {
     if (!$model->canGetProperty('idAttribute')) {
         throw new \LogicException("Model {$model->className()} has not 'idAttribute' property");
     }
     $modelName = $this->getShortClass($model);
     /** @noinspection PhpUndefinedFieldInspection */
     $modelId = $model->{$model->idAttribute};
     return $this->_getSubDirectory($modelName, $modelId);
 }
Example #24
0
 /**
  * Init.
  * @throws InvalidConfigException
  */
 public function init()
 {
     parent::init();
     if (!isset($this->id)) {
         throw new InvalidConfigException(get_class($this) . '::$id');
     }
     if (!$this->model instanceof Model) {
         throw new InvalidConfigException(get_class($this) . '::$model');
     }
     $this->model->setScenario('sync');
 }
 /**
  * @param string $prompt
  * @param \yii\base\Model $model
  * @param string $field
  * @param string $default
  * @return string
  */
 private function readStdinUser($prompt, $model, $field, $default = '')
 {
     while (!isset($input) || !$model->validate(array($field))) {
         echo $prompt . ($default ? " [{$default}]" : '') . ': ';
         $input = trim(fgets(STDIN));
         if (empty($input) && !empty($default)) {
             $input = $default;
         }
         $model->{$field} = $input;
     }
     return $input;
 }
 /**
  * @param Model $model
  * @param string $attribute
  */
 private function readValue($model, $attribute)
 {
     $model->{$attribute} = $this->prompt(mb_convert_case($attribute, MB_CASE_TITLE, 'utf-8') . ':', ['validator' => function ($input, &$error) use($model, $attribute) {
         $model->{$attribute} = $input;
         if ($model->validate([$attribute])) {
             return true;
         } else {
             $error = implode(',', $model->getErrors($attribute));
             return false;
         }
     }]);
 }
Example #27
0
 /**
  * Move current model after another specified model (ie. `$model->moveAfter($another_model);`)
  * Note: you must manually call refresh() on needed models
  * @param \yii\base\Model $another_model Model taht would be before current model
  */
 public function moveAfter($another_model)
 {
     $field = $this->attribute;
     //! @todo Переписать эти два запроса на один, использующий CASE WHEN THEN
     // shift sort_order field for current model and below
     Yii::$app->db->createCommand("UPDATE " . $this->owner->tableName() . " SET {$field} = {$field} + 1 WHERE {$field} >= :model_sort_order", [':model_sort_order' => intval($another_model->getAttribute($field)) + 1])->execute();
     // shift sort_order field for records upper current
     Yii::$app->db->createCommand("UPDATE " . $this->owner->tableName() . " SET {$field} = {$field} - 1 WHERE {$field} <= :model_sort_order_lower AND {$field} >= :model_sort_order_upper", [':model_sort_order_lower' => intval($another_model->getAttribute($field)) + 1, ':model_sort_order_upper' => intval($this->owner->getAttribute($field))])->execute();
     // change sort_order of our record
     $this->owner->setAttribute($field, $another_model->getAttribute($field));
     $this->owner->save(false, [$field]);
 }
Example #28
0
 /**
  * Helper method to correctly send model erros and add correct response headers.
  *
  * @param ActiveRecordInterface $model
  * @throws ServerErrorHttpException
  * @return array
  */
 public function sendModelError(Model $model)
 {
     if (!$model->hasErrors()) {
         throw new ServerErrorHttpException('Object error for unknown reason.');
     }
     Yii::$app->response->setStatusCode(422, 'Data Validation Failed.');
     $result = [];
     foreach ($model->getFirstErrors() as $name => $message) {
         $result[] = ['field' => $name, 'message' => $message];
     }
     return $result;
 }
Example #29
0
 /**
  * Validate Form action
  * @param Model $model
  * @param string $action
  * @return array
  */
 public function setAjaxData(Model $model, $action = 'save', $json = false)
 {
     $response = ['status' => 0, 'errors' => '', 'text' => ''];
     if (\Yii::$app->request->isAjax && $model->load(\Yii::$app->request->post())) {
         if ($model->{$action}()) {
             $response['status'] = 1;
         } else {
             $response['errors'] = Html::errorSummary($model);
         }
     }
     return $json ? json_encode($response) : [$model, $response];
 }
Example #30
0
 protected function saveItem($id, $value)
 {
     $exist = Config::findOne($id);
     if ($exist) {
         Config::updateAll(['value' => $value], ['id' => $id]);
     } else {
         $model = new Model();
         $model->scope = $this->scope;
         $model->id = $id;
         $model->value = $value;
         $model->description = $id;
         $model->save();
     }
 }