【问题标题】:How to through error message in Yii2 Api?如何通过 Yii2 Api 中的错误消息?
【发布时间】:2018-03-18 02:56:59
【问题描述】:

这是附上的代码。 如果缺少任何属性,如何抛出错误消息? 我需要检查所有属性是否来自表单。如果缺少任何属性,我想使用正确的错误代码抛出错误消息。

$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;
}

【问题讨论】:

  • 你读过一些关于在 Yii2 中处理用户输入的文章吗?你的代码不是 Yii2 代码,它是纯 PHP。
  • 为什么不加载属性,应用 validate() 然后检查 $model->errors ? $模型->属性= $_POST; $model->validate();
  • 这非常简单。如果您添加了模型的代码,您将能够更轻松地获得帮助

标签: api error-handling yii2 error-code


【解决方案1】:

这是我实现目标的代码。

$model = 新的注册表格;

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();
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多