使Yii2中的用户可以选择FileInput

使Yii2中的用户可以选择FileInput,yii2,Yii2,我的表单中有一个文件输入字段,可以很好地上传文件。但我想为用户保留一项规定,即他们可能根本不会上传任何文件 我的代码如下所示- 示范规则- [['jha'],'file','skipOnEmpty' => true,'extensions' => 'pdf'], 形式 根据这段代码,如果我保持上载字段不变,我会得到错误- Call to a member function saveAs() on null 在saveAs()之前选中empty 在saveAs()之前选中empty

我的表单中有一个文件输入字段,可以很好地上传文件。但我想为用户保留一项规定,即他们可能根本不会上传任何文件

我的代码如下所示-

示范规则-

[['jha'],'file','skipOnEmpty' => true,'extensions' => 'pdf'],
形式

根据这段代码,如果我保持上载字段不变,我会得到错误-

Call to a member function saveAs() on null

saveAs()之前选中
empty


saveAs()之前选中
empty

public function actionCreatenewworkbasic()
    {


       $model = new Workpermit();
       $model->wp_timeissued = date('Y-m-d H:i:s');

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

       {

           $timenow = date('-Y-m-d-H-i-s');
           $model->jha = UploadedFile::getInstance($model,'jha');
           $model->jha->saveAs('uploads/jha/'.$model->jha->baseName.$timenow.'.'.$model->jha->extension);

           //save the path in the db

           $model->wp_jhaattach = 'uploads/jha/'.$model->jha->baseName.$timenow.'.'.$model->jha->extension;

           $model->jha = null;
           $model->save(false);


           return $this->redirect(['availablework']); 
       }else{
            return $this->renderAjax('createnewworkbasic', [
               'model' => $model,
            ]);
       }      
    }
Call to a member function saveAs() on null
if ($model->load(Yii::$app->request->post())) {

    $timenow = date('-Y-m-d-H-i-s');
    $model->jha = UploadedFile::getInstance($model,'jha');

    if (!empty($model->jha)) {
       $model->jha->saveAs('uploads/jha/'.$model->jha->baseName.$timenow.'.'.$model->jha->extension);

       //save the path in the db

       $model->wp_jhaattach = 'uploads/jha/'.$model->jha->baseName.$timenow.'.'.$model->jha->extension;
    }

    $model->jha = null;
    $model->save(false);

    return $this->redirect(['availablework']);
}