`Skip on empty` not working in Yii2 file upload

前端 未结 2 1410
我在风中等你
我在风中等你 2021-01-05 12:52

I have a provision to upload logo for companies in my application. Uploading and saving on creating profile works fine. But on update, logo goes empty if I am not uploading

相关标签:
2条回答
  • 2021-01-05 13:30
    'skipOnEmpty' => !$this->isNewRecord
    

    For update it can be skipped.

    0 讨论(0)
  • 2021-01-05 13:36

    skipOnEmpty does not apply here because in the update action the $model->logo attribute will not be empty, it will be a string with the file name.$file is still an array with only keys, but not values if not uploaded again. So checked the $file->size instead of checking !empty($file). Fixed the issue by modifying the controller code as follows!

        $model = $this->findModel($id);
        $current_image = $model->featured_image;
        if ($model->load(Yii::$app->request->post())) {         
            $image= UploadedFile::getInstance($model, 'featured_image');
            if(!empty($image) && $image->size !== 0) {
                //print_R($image);die;
                $image->saveAs('uploads/' . $image->baseName . '.' .$image->extension);
                $model->featured_image = 'uploads/'.$image->baseName.'.'.$image->extension; 
            }
            else
                $model->featured_image = $current_image;
            $model->save();
            return $this->redirect(['update', 'id' => $model->module_id]);
        } else {
            return $this->render('add', [
                'model' => $model,
            ]);
        }
    
    0 讨论(0)
提交回复
热议问题