2017-07-06 64 views
-1

我想添加Ajax驗證,以在更新之前檢查表單。在視圖中,加入到必需字段如何避免使用ajax驗證即時保存模型?

['enableAjaxValidation' => true] 

在控制器中actionUpdate

if (Yii::$app->request->isAjax && $modelForm->load(Yii::$app->request->post())) { 
      Yii::$app->response->format = Response::FORMAT_JSON; 
      if ($modelForm->validate()) { 
       $model->setAttributes($modelForm->getAttributes()); 

       if ($model->save()) { 
        return $this->redirect([my way]); 
       } 

       if ($model->hasErrors()) { 
        return ActiveForm::validate($model); 
       } else { 
        return ['success' => 1, 'html' => 
         $this->renderPartial('view', [my data]; 
       } 
      } else { 
       return ActiveForm::validate($modelForm); 
      } 
     } 

的問題是,在該領域的任何值,這是「enableAjaxValidation」 =>真的選擇,立即導致保存模型(即使沒有按下保存按鈕)。這怎麼可以避免?

回答

1

在控制器嘗試這樣的:

$model = new ExampleForm; 

// validate any AJAX requests fired off by the form 
if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) { 
    Yii::$app->response->format = Response::FORMAT_JSON; 
    return ActiveForm::validate($model); 
} 

從你的if語句您if語句之前添加這一點,並刪除Yii::$app->request->isAjax

0

添加一些東西象下面這樣的形式

$form = ActiveForm::begin([ 
      'id' => 'example', 
      'action' => ['your_action'], 
      'validateOnSubmit' => true, 
      'enableAjaxValidation' => true, 
     ]) 
+0

這不會幫助他,因爲Ajax請求仍然會保存模型。他的行爲不處理Ajax請求。 – Yupik

+0

@Yupik但只有當他們點擊保存按鈕時纔會發生ajax。 –

+0

但他不想刪除模糊的ajax驗證,他不想在ajax驗證上保存模型。並且,就您的情況而言,它將通過點擊發送按鈕(一個模型保存)進行驗證,發送表單將第二次保存。 – Yupik