2015-12-24 73 views
0

我是Yii的新手,無法弄清楚ajax驗證如何與ActiveForm配合使用。 在我的模型我有獨特的領域:使用Ajax,Yii2驗證唯一字段ActiveForm

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}".' 
      ], 
     ]; 
    } 

的比較規則驗證與阿賈克斯和工作正常,但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來顯示錯誤。

+0

顯示控制器代碼,請... –

+0

@DoubleH,更新 –

+0

@DoubleH,更新 –

回答

1

您需要在控制器中使用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 
     ]); 
} 
} 
1

試試這個代碼在你的控制器......

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 
    ]); 
} 
} 
+1

您不應該使用'Json :: encode',要麼隨時更改響應格式,要麼使用'ContentNegotiator'。 – arogachev