[英]Validate unique field using Ajax, Yii2 ActiveForm
我是Yii的新手,无法弄清楚ActiveForm
如何使用Ajax验证。 在我的模型中,我有一个独特的领域:
public function rules()
{
return [
//...
[['end_date'], 'unique'], //ajax is not working
[ 'end_date', //ajax is working
'compare',
'compareAttribute'=>'start_date',
'operator'=>'>=',
'skipOnEmpty'=>true,
'message'=>'{attribute} must be greater or equal to "{compareValue}".'
],
];
}
比较规则已使用ajax验证并且可以正常工作,但unique
则不行。 我试图在表单上启用Ajax验证:
<?php $form = ActiveForm::begin( ['id' => 'routingForm', 'enableClientValidation' => true, 'enableAjaxValidation' => true]); ?>
但是不知道下一步该怎么做。
控制器:
public function actionCreate()
{
$model = new Routing();
$cities = [];
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['index']);
} else {
return $this->renderAjax('create', [
'model' => $model,
'cities' => $cities
]);
}
}
我知道我可以做AJAX调用控制器上end_date
变化事件,形成submit
,但不知道如何作出一切适当的CSS来显示错误。
您需要在控制器中使用Yii::$app->request->isAjax
。
public function actionCreate()
{
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) {
Yii::$app->response->format = \yii\web\Response::FORMAT_JSON;
return ActiveForm::validate($model);
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['index']);
} else {
return $this->renderAjax('create', [
'model' => $model,
'cities' => $cities
]);
}
}
在您的控制器中尝试此代码...
public function actionCreate()
{
$model = new Routing();
$cities = [];
if(Yii::$app->request->isAjax){
$model->load(Yii::$app->request->post());
return Json::encode(\yii\widgets\ActiveForm::validate($model));
}
if ($model->load(Yii::$app->request->post()) && $model->save()) {
return $this->redirect(['index']);
} else {
return $this->renderAjax('create', [
'model' => $model,
'cities' => $cities
]);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.