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.