doujiurong7210
2016-03-05 07:03
浏览 87
已采纳

在yii2中保存之前验证内容

I am using yii2 for a weigh bridge project

Upon create, the user is redirected to view but my controller doesn't validate the information in such a way that even if data is not entered in the form fields a user is always redirected to view.

How can I implement the validation property

Controller code:

 public function actionCreate()
{
    $model = new TruckWeight1();

    if ($model->load(Yii::$app->request->post()) ) {

        $model->time_recorded =date('H:i:s');;
        $model->recorded_by =
        $model->recorded_date = date('Y-m-d');

        $model->save();

        return $this->redirect(['view', 'id' => $model->id]);

    } else {
        return $this->render('create', [
            'model' => $model,
        ]);
    }
}

图片转代码服务由CSDN问答提供 功能建议

我正在使用 yii2 进行称重桥项目

创建后,用户将被重定向到查看,但我的控制器不会以这样的方式验证信息:即使未在表单字段中输入数据,用户也始终会重定向到查看。

如何实现验证属性

控制器代码:

  public function actionCreate(  )
 {
 $ model = new TruckWeight1(); 
 
 if if($ model-> load(Yii :: $ app-> request-> post())){
 
 $  model-> time_recorded = date('H:i:s');; 
 $ model-> recorded_by = 
 $ model-> recorded_date = date('Ym-d'); 
 
 $  model-> save(); 
 
返回$ this-> redirect(['view','id'=> $ model-> id]); 
 
} else {
返回 $ this-> render('create',[
'model'=> $ model,
]); 
} 
} 
   
 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • dongshao1021 2016-03-05 07:26
    已采纳

    try this

    public function actionCreate()
    {
        $model = new TruckWeight1();
    
        if ($model->load(Yii::$app->request->post()) && $model->validate()) {
    
            $model->time_recorded =date('H:i:s');;
            $model->recorded_by =
            $model->recorded_date = date('Y-m-d');
    
            $model->save();
    
            return $this->redirect(['view', 'id' => $model->id]);
    
        } else {
            return $this->render('create', [
                'model' => $model,
            ]);
        }
    }
    

    for more on validation validation

    打赏 评论