Returns the errors for all attributes or a single attribute.
public getErrors ( string $attribute = null ) : array | ||
$attribute | string | attribute name. Use null to retrieve errors for all attributes. |
Résultat | array | errors for all attributes or the specified attribute. Empty array is returned if no error. Note that when returning errors for all attributes, the result is a two-dimensional array, like the following: ```php [ 'username' => [ 'Username is required.', 'Username must contain only word characters.', ], 'email' => [ 'Email address is invalid.', ] ] ``` |
/** * @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); }
/** * @param \yii\base\Model * @param string $default_attribute * @param array $attributes_map */ public function populateErrors(\yii\base\Model $Model, $default_attribute, $attributes_map = []) { $errors = $Model->getErrors(); foreach ($errors as $attribute => $messages) { $attribute = isset($attributes_map[$attribute]) ? $attributes_map[$attribute] : $attribute; if (false === $this->hasProperty($attribute)) { if (!method_exists($this, 'hasAttribute')) { $attribute = $default_attribute; } elseif (false === $this->hasAttribute($attribute)) { $attribute = $default_attribute; } } foreach ($messages as $mes) { $this->addError($attribute, $mes); } } }
/** * @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; } }]); }
/** * @param Model $model * @throws JqException */ public static function throwModel($model) { $errors = $model->getErrors(); if (empty($errors)) { return; } $message = ''; foreach ($errors as $name => $error) { if (!is_array($error)) { continue; } $message .= $name . ': '; foreach ($error as $e) { $message .= $e . '; '; } } throw new self($message); }
/** * Валидация атрибутов. * * На вход передается модель для валидации и массив значений для валидации. * Массив значений должен иметь следующий формат: * ```php * array( * '<attribute1>' => array( * array( * 'value' => <mixed>, // значение для валидации * 'isValid' => <boolean>, // true, если значение должно проходить валидацию * ), * ), * ) * ``` * * Проверяет, что атрибут либо должен проходить проверку валидации, либо не должен. * * @param Model $model проверяемая модель * @param array $attributes массив значений атрибутов для валидации */ protected function validateAttributes(Model $model, $attributes) { foreach ($attributes as $attribute => $values) { $attributeTitle = $model->getAttributeLabel($attribute); foreach ($values as $v) { $value = $v['value']; $isValid = $v['isValid']; $model->{$attribute} = $value; if ($isValid) { $message = $attributeTitle . ' validation error: ' . implode("\n", $model->getErrors($attribute)); $message .= "\nAsserting value: " . print_r($value, true); $this->assertTrue($model->validate([$attribute]), $message); } else { $message = $attributeTitle . ' must be invalid' . "\n"; $message .= 'Asserting value: ' . print_r($value, true); $this->assertFalse($model->validate([$attribute]), $message); } } } }
/** * Validates one or several models and returns an error message array indexed by the attribute IDs. * This is a helper method that simplifies the way of writing AJAX validation code. * * For example, you may use the following code in a controller action to respond * to an AJAX validation request: * * ```php * $model = new Post; * $model->load($_POST); * if (Yii::$app->request->isAjax) { * Yii::$app->response->format = Response::FORMAT_JSON; * return ActiveForm::validate($model); * } * // ... respond to non-AJAX request ... * ``` * * To validate multiple models, simply pass each model as a parameter to this method, like * the following: * * ```php * ActiveForm::validate($model1, $model2, ...); * ``` * * @param Model $model the model to be validated * @param mixed $attributes list of attributes that should be validated. * If this parameter is empty, it means any attribute listed in the applicable * validation rules should be validated. * * When this method is used to validate multiple models, this parameter will be interpreted * as a model. * * @return array the error message array indexed by the attribute IDs. */ public static function validate($model, $attributes = null) { $result = []; if ($attributes instanceof Model) { // validating multiple models $models = func_get_args(); $attributes = null; } else { $models = [$model]; } /* @var $model Model */ foreach ($models as $model) { $model->validate($attributes); foreach ($model->getErrors() as $attribute => $errors) { $result[Html::getInputId($model, $attribute)] = $errors; } } return $result; }
/** * @param \yii\base\Model $model */ public static function addModelErrors($model) { $errors = $model->getErrors(); self::addError(self::flatten($errors)); }
/** * @param Model $model * @param string $glue * @return string */ public static function formatModelErrors(Model $model, $glue = PHP_EOL) { return implode($glue, array_map(function ($item) { return is_array($item) ? array_pop($item) : $item; }, $model->getErrors())); }
function __construct(\yii\base\Model $model) { parent::__construct('model.validation.error', null, $model->getErrors()); }