[英]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.