[英]Yii2 validation on controller action
我正在開發一個Yii 2.0應用程序,用戶可以在其中創建訂單,然后將訂單發送給審閱,此后它遵循工作流程中的多個階段。
一切正常,直到昨天客戶要求在發送訂單以查看訂單之前將其視為草稿。 這意味着我必須關閉對create的驗證,並在用戶單擊Send To Review按鈕時驗證它們。 我知道Yii 2.0支持方案,但方案可能不適用於此方案,因為“發送至審閱”按鈕顯示在只讀視圖中。 因為沒有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:自動重定向以更新控制器中已設置的方案和驗證錯誤的視圖。
謝謝,
最好的祝福
您可以使用$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()
驗證, actionCreate()
創建一個不驗證任何字段的方案並在那里應用。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.