如何通过Yii2 Api中的错误消息?
问题描述:
下面是附加的代码。 如果缺少任何属性,我该如何抛出错误信息? 我需要检查所有属性是否来自窗体或不。如果缺少任何属性,我想用适当的错误代码抛出错误消息。如何通过Yii2 Api中的错误消息?
$get_email = Null;
$get_password = Null;
$get_username = Null;
if (isset($_POST['username'])) {
$get_username = $_POST['username'];
}
if (isset($_POST['email']) && isset($_POST['password'])) {
$get_email = $_POST['email'];
$get_password = $_POST['password'];
}
if ($get_email == Null || $get_username == Null || $get_password == Null) {
// through error code with message
}
else {
$model = new SignupForm();
$model->email = $get_email;
$model->username = $get_username;
$model->password = $get_password;
}
答
这是通过它实现我的目标的代码。
$ model = new SignupForm;
if (isset($_POST['username'])) {
$model->username = $_POST['username'];
}
if (isset($_POST['email'])) {
$model->email = $_POST['email'];
}
if (isset($_POST['password'])) {
$model->password = $_POST['password'];
}
if($model->validate()){
$model->signup();
}
else{
return $model->getErrors();
}
你甚至读过关于在Yii2中处理用户输入的内容吗?你的代码不是Yii2代码,它是纯PHP。 – Yupik
为什么不加载属性,应用validate()然后检查$ model-> errors? $ model-> attributes = $ _POST; $模型 - >的validate(); –
这非常直截了当。如果您为模型添加了代码,您将能够更轻松地获得帮助 – mrateb