php - Yii2唯一验证错误:数组到字符串的转换

标签 php ajax validation yii2 yii2-advanced-app

我遵循了Yii2 Documentation上提到的完全相同的过程,但是在AJAX验证中出现了数组到字符串转换错误。

方案:在SignUp表单中启用AJAX验证,包括服务器端验证,例如电子邮件唯一验证。

在 View 中进行的更改

use yii\widgets\ActiveForm;

<?php $form = ActiveForm::begin([
    'id' => 'form-signup',
    'enableAjaxValidation' => true,
]); ?>

在 Controller 中进行的更改
use yii\web\Response;
use yii\widgets\ActiveForm;

if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
    Yii::$app->response->format = Response::FORMAT_JSON;
    return ActiveForm::validate($model);
}

**注册小部件**
<?php
namespace frontend\components;

use Yii;
use frontend\models\SignupForm;
use common\models\User;
use yii\base\Widget;
use yii\web\Response;
use yii\widgets\ActiveForm;

/**
 * SignUpFormWidget is a widget that provides user signup functionality.
 */
class SignUpFormWidget extends Widget
{
    /**
     * @var string the widget title. Defaults to 'Register'.
     */
    public $title='Register';
    /**
     * @var boolean whether the widget is visible. Defaults to true.
     */
    public $visible = true;

    public function run()
    {
        if($this->visible) {
            $model = new SignupForm();

            if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
                Yii::$app->response->format = Response::FORMAT_JSON;
                return ActiveForm::validate($model);
            }

            if ($model->load(Yii::$app->request->post())) {
                if ($user = $model->signup()) {
                    if (Yii::$app->getUser()->login($user)) {
                        return $this->goHome();
                    }
                }
            }

            return $this->render('signUpWidget', [
                'model' => $model,
            ]);
        }
    }
}

错误
[error][yii\base\ErrorException:8] exception 'yii\base\ErrorException' with message 'Array to string conversion' \vendor\yiisoft\yii2\base\Widget.php:107
我尝试使用json_encode($error),但是它的重装页面无法重载,因为寄存器形式位于隐藏div下的 header 上。我创建了SignUpFormWidget,它扩展了Widget。

请提出建议,我在这里想念的是什么?

最佳答案

您的错误是因为Widget::run()方法期望返回字符串。 ActiveFrom::validate()返回一个数组。如上面的@DoubleH所建议,您需要将代码重新编写为

if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {

   Yii::$app->response->format = Response::FORMAT_JSON;
   return yii\helpers\Json::encode(\yii\widgets\ActiveForm::validate($model));
}

关于php - Yii2唯一验证错误:数组到字符串的转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34388158/

相关文章:

cocoa - 如何在 Mac OS X 中测试有效的文件名

c - 在 Linux 上正则化 C 中不存在的路径

php - 通过 htaccess 更改地址栏

php - 如何使用 Ajax 在页面上显示 PHP 服务器端验证消息

使用输入字段属性(无需 eval)的 Javascript 正则表达式验证

javascript - 使用 Ajax 请求设置 Cookie

jquery - 如何在标准 Web 表单 .Net 中返回 JSON 对象

php - 具有 varchar id 的 Doctrine2 实体不将 id 插入数据库

php - error_message 变量在表单提交时不显示字符串值

php - 如何在中间件 Laravel 5 中捕获 "too many attempt"异常