0

I am trying to check if the field input is empty or not and upload a file depending on that.

My code in the controller is as below:

public function actionCreate()
{

    // set default values

    $model = new Tasks();
    $model->priotiy_level = 'medium';
    $model->start_date = date('Y-m-d'); //to get default date

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


        //Check if field input is empty

        $file = UploadedFile::getInstance($model, 'upload_documents');
        if ($file->size !== 0)

        {
            //get instance of uploaded file
            $fName = time();
            $model->file = UploadedFile::getInstance($model, 'upload_documents');
            $model->file->saveAs('uploads/'.$fName.'.'.$model->file->extension);

            $model->upload_documents = 'uploads/'.$fName.'.'.$model->file->extension;
        }
        $model->save();

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

Code in form is as below:

<?= $form->field($model, 'upload_documents')->fileInput(); ?>

At the if() condition I keep getting the error "Trying to get property of non-object"

Can someone please help me out with this?

I just want to upload file if the field isn't empty.

Thank you.

IStranger
  • 1,868
  • 15
  • 23
user2211486
  • 237
  • 1
  • 6
  • 18

1 Answers1

1

Found the answer on another question asked (took some time to find that question). Yii2 FileInput - Trying to get property of non object

Had to use if($model->file){ } instead of what I was using.

$model->file = UploadedFile::getInstance($model, 'upload_documents');


        if($model->file)
        {
            //get instance of uploaded file
            $fName = time();
            $model->file = UploadedFile::getInstance($model, 'upload_documents');
            $model->file->saveAs('uploads/'.$fName.'.'.$model->file->extension);

            $model->upload_documents = 'uploads/'.$fName.'.'.$model->file->extension;
        }
        $model->save();
Community
  • 1
  • 1
user2211486
  • 237
  • 1
  • 6
  • 18