[英]Validate unique field using Ajax, Yii2 ActiveForm
I am new to Yii, and cannot figure out how ajax validation works with ActiveForm
. 我是Yii的新手,无法弄清楚
ActiveForm
如何使用Ajax验证。 In my model I have unique field: 在我的模型中,我有一个独特的领域:
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}".'
],
];
}
The compare rule is validated with ajax and works fine, but unique
is not. 比较规则已使用ajax验证并且可以正常工作,但
unique
则不行。 I tried to enable ajax validation on form: 我试图在表单上启用Ajax验证:
<?php $form = ActiveForm::begin( ['id' => 'routingForm', 'enableClientValidation' => true, 'enableAjaxValidation' => true]); ?>
But don't know what to do next. 但是不知道下一步该怎么做。
Controller: 控制器:
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
]);
}
}
I know I could make ajax call to controller on end_date
change event and form submit
, but not sure how make all appropriate css to show the errors. 我知道我可以做AJAX调用控制器上
end_date
变化事件,形成submit
,但不知道如何作出一切适当的CSS来显示错误。
You need to use Yii::$app->request->isAjax
in controller. 您需要在控制器中使用
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
]);
}
}
Try this code in your controller... 在您的控制器中尝试此代码...
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.