2016-10-01 77 views
0

我正在開發一個Yii 2.0應用程序,用戶可以在其中創建訂單,然後發送訂單進行審閱,然後在工作流中執行多個階段。Yii2對控制器動作的驗證

一切都很好,直到昨天,客戶要求在發送訂單審覈訂單之前的可能性被視爲草稿。這意味着當用戶點擊Send To Review按鈕時,我必須關閉創建驗證並驗證它們。我知道Yii 2.0支持方案,但可能情況不適用於此,因爲Send To Review按鈕顯示在只讀視圖中。這迫使我在控制器操作中進行驗證,因爲沒有send_to_review視圖。如何做到這一點(我的意思是控制器內部的模型驗證)?

這裏是控制器動作代碼

public function actionSendToReview($id) 
{ 
    if (Yii::$app->user->can('Salesperson')) 
    { 
     $model = $this->findModel($id); 
     if ($model->orden_stage_id == 1 && $model->sales_person_id == Yii::$app->user->identity->id) 
     { 
      $model->orden_stage_id = 2; 
      $model->date_modified = date('Y-m-d h:m:s'); 
      $model->modified_by = Yii::$app->user->identity->username; 

      //TODO: Validation logic if is not valid show validation errors 
      //for example "For sending to review this values are required: 
      //list of attributes in bullets" 
      //A preferred way would be to auto redirect to update action but 
      //showing the validation error and setting scenario to    
      //"send_to_review". 


      $model->save(); 
      $this::insertStageHistory($model->order_id, 2); 
      return $this->redirect(['index']); 
     } 
     else 
     { 
      throw new ForbiddenHttpException(); 
     } 
    } 
    else 
    { 
     throw new ForbiddenHttpException(); 
    } 
} 

我需要解決的是TODO。 選項1:在同一視圖中顯示驗證錯誤,並且用戶必須點擊更新按鈕更改所請求的值保存,然後嘗試再次發送到評論。 選項2:自動重定向更新視圖,已經設置了控制器中發現的場景和驗證錯誤。

感謝,

問候

回答

0

可以在控制器使用$model ->validate()進行驗證。

public function actionSendToReview($id) 
{ 
    if (Yii::$app->user->can('Salesperson')) 
    { 
     $model = $this->findModel($id); 
     if ($model->orden_stage_id == 1 && $model->sales_person_id == Yii::$app->user->identity->id) 
     { 
      $model->orden_stage_id = 2; 
      $model->date_modified = date('Y-m-d h:m:s'); 
      $model->modified_by = Yii::$app->user->identity->username; 



      //TODO: Validation logic if is not valid show validation errors 
      //for example "For sending to review this values are required: 
      //list of attributes in bullets" 
      //A preferred way would be to auto redirect to update action but 
      //showing the validation error and setting scenario to    
      //"send_to_review". 

      //optional 
      $model->scenario=//put here the scenario for validation; 

      //if everything is validated as per scenario 
      if($model ->validate()) 
      {     
       $model->save(); 
       $this::insertStageHistory($model->order_id, 2); 
       return $this->redirect(['index']); 
      } 
      else 
      { 
       return $this->render('update', [ 
       'model' => $model, 
       ]); 
      } 


     } 
     else 
     { 
      throw new ForbiddenHttpException(); 
     } 
    } 
    else 
    { 
     throw new ForbiddenHttpException(); 
    } 
} 

如果您不需要actionCreate() .Create方案驗證不驗證任何領域和應用存在。

+0

它工作正常,但現在驗證錯誤顯示兩次。奇怪的 –