2016-10-23 32 views
0

我想在yii2中進行自定義驗證,但這不起作用。在yii2表單驗證中顯示錯誤

我想什麼是驗證每當卡車狀態不是17或18即如果例如它的12應返回該錯誤,但始終顯示錯誤

public function validateRegno() 
{ 
    $truck = TblTrucks::find()->where(["reg_no"=>$this->reg_no])->all(); 

    if ($truck) { 
     if(!$truck->truck_status ==18 || !$truck->truck_status ==17){ 
      $this->addError('reg_no', 'The truck is not yet cleared by customer service'); 
     } 


    } 
} 

這些都是模型的規則

public function rules() 
{ 
    return [ 
     [['reg_no', 'truck_category', 'added_by', 'truck_status', 'driver_name'], 'required'], 
     [['truck_category', 'added_by', 'truck_status', 'is_normal'], 'integer'], 
     [['added_on'], 'safe'], 
     [['reg_no'], 'string', 'max' => 50], 

     ['reg_no', 'validateRegno','on' => 'create'], 

} 

這是我的形式

<?php $form = ActiveForm::begin(['id' => $model->formName(), 
     'enableAjaxValidation' => true, 
     //'enableClientValidation' => true, 
     'validationUrl' => ['truck/validate'], 

    ]); ?> 

在控制器

(truck/validate) 
    public function actionValidate(){ 
    $model = new TblTrucks(); 
    $model->scenario = 'create'; 
    if (Yii::$app->request->isAjax && $model->load(Yii::$app->request->post())) { 

     if (!$model->validate()) { 
      Yii::$app->response->format='json'; 
      return ActiveForm::validate($model); 
     } 
    } 
} 
+0

在表單上使用''enableAjaxValidation'=> true'並且添加'if(Yii :: $ app-> request-> isAjax && $ model-> load(Yii :: $ ()){ Yii :: $ app-> response-> format = \ yii \ web \ Response :: FORMAT_JSON; return ActiveForm :: validate($ model); }'在行動部分 – GAMITG

+0

但它沒有這樣做 –

+0

你會得到錯誤? – GAMITG

回答

0

您的自定義驗證方法應該如下所示。

public function validateRegno() 
{ 
    $truck = TblTrucks::find()->where(["reg_no"=>$this->reg_no])->all(); 

    if ($truck) { 
     if(!$truck->truck_status ==18 || !$truck->truck_status ==17){ 
      $this->addError('reg_no', 'The truck is not yet cleared by customer service'); 
     } 


    } 
} 

我希望在你的模型,$this->reg_no是我的意思是自動遞增場主鍵字段。所以在創建新記錄時,它將是空的。

編輯:

根據您的評論,$this->reg_no是不是在模型中的主鍵。在使用all()檢索記錄時,它將返回記錄數組。請參閱此鏈接 - http://www.yiiframework.com/doc-2.0/yii-db-queryinterface.html#all()-detail因此,您必須迭代記錄以檢查每輛卡車的狀態。

否則$this->reg_no在表中是唯一的,您必須使用one()方法來檢索記錄。它將從表中返回單個記錄。請參考文檔one() - http://www.yiiframework.com/doc-2.0/yii-db-queryinterface.html#one()-detail

+0

它與我在問題中發佈的內容有什麼不同 –

+0

@GEOFFREYMWANGI請檢查* validateRegno *方法,我刪除了查詢以及條件。在你的情況下,我不需要感覺。 –

+0

最新情況是,在註冊期間ama檢查,看看是否有一輛卡車有類似的reg_no,所以我們不能假設爲空,reg_no不是自動增量 –