model method to get errors:
public static function getModelError($model) { $errors = $model->getErrors(); //得到所有的错误信息 if(!is_array($errors)) return ''; $firstError = array_shift($errors); if(!is_array($firstError)) return ''; return array_shift($firstError); }
getErrors(): Returns errors for all attributes or a single attribute, that is, returns all errors that occurred during validation.
Usage examples are as follows:
$model = new User(); $model->name = $name; $model->nick_name = $nick_name; $model->phone = $phone; $model->sex = $sex; $model->isNewRecord = true; //此语句可省略 if(!$model->save()){ //保存不成功 throw new \RuntimeException('保存败.'.$model::getModelError($model)); }
PHP Chinese website has a large number of free Yii introductory tutorials, everyone is welcome to learn!
The above is the detailed content of How to get errors in yii model. For more information, please follow other related articles on the PHP Chinese website!