Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

`Skip on empty` not working in Yii2 file upload

Tags:

yii

yii2

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 it again!

Here's my update form

    <?php $form = ActiveForm::begin([
                'options' => ['enctype'=>'multipart/form-data']
        ]); ?>

       .....

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

       ...

My Controller action

    if ($model->load($_POST) ) {
    $file = \yii\web\UploadedFile::getInstance($model, 'logo');
    if($file){
    $model->logo=$file; }

    if($model->save()){

        if($file)
        $file->saveAs(\Yii::$app->basePath . '/web/images/'.$file);
        }

            return $this->redirect(['profile']);
        } else {
            return $this->renderPartial('update', [
                'model' => $model,
            ]);
        }

My Rules:

public function rules()
{
    return [

        [['logo'], 'image', 'extensions' => 'jpg,png', 'skipOnEmpty' => true],
        [['name'], 'required'],
        [['name', 'description'], 'string'],

    ];
}

Any ideas????

like image 203
Dency G B Avatar asked Aug 11 '14 07:08

Dency G B


2 Answers

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,
        ]);
    }
like image 137
Dency G B Avatar answered Sep 28 '22 18:09

Dency G B


'skipOnEmpty' => !$this->isNewRecord

For update it can be skipped.

like image 37
Val Avatar answered Sep 28 '22 16:09

Val