[英]Yii2 unique validation error: Array to string conversion
我遵循了Yii2文档中提到的完全相同的过程,但是我在AJAX验证时遇到了Array to string conversion错误。
场景:以SignUp形式启用AJAX验证,包括服务器端验证,如电子邮件唯一验证。
在视图中进行的更改
use yii\widgets\ActiveForm;
<?php $form = ActiveForm::begin([
'id' => 'form-signup',
'enableAjaxValidation' => true,
]); ?>
控制器中的更改
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);
}
** SignUp小工具**
<?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下的标题上。 我创建了扩展Widget的SignUpFormWidget。
请建议,我在这里缺少什么?
将您的控制器代码更新为
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));
}
您的错误是因为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));
}
您正在使用此Yii::$app->response->format = Response::FORMAT_JSON;
这意味着你在数组中获得价值。所以尝试从数组中获取值然后验证它,或者只是在注释中注释它。 您无法将数组验证为字符串,因此它会给您错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.