0

I can not update if I do not select an image. What do wrong or I'm missing?

This is a controller:

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

        $nameImage=$model->name;

        $model->bookimg=UploadedFile::getInstance($model,'bookimg');
        $model->bookimg->saveAs('images/'.$nameImage.'.'.$model->bookimg->extension);

        $model->bookimg='images/'.$nameImage.'.'.$model->bookimg->extension;
        $model->save();

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

This is a model:

[['fkperiodo'], 'integer'],
[['date_public'], 'safe'],
[['name'], 'string', 'max' => 100],
[['volume'], 'string', 'max' => 5],
[['author',], 'string', 'max' => 255],
[['bookimg'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg'],
[['fkperiod'], 'exist', 'skipOnError' => true, 'targetClass' => Period::className(), 'targetAttribute' => ['fkperiod' => 'id']],

This is a form:

<?= $form->field($model, 'bookimg')->fileInput()->label('Book Cover') ?>
Kostas Mitsarakis
  • 4,772
  • 3
  • 23
  • 37
Juam
  • 11
  • 3
  • http://stackoverflow.com/questions/37746082/call-to-a-member-function-saveas-on-nulldoest-work-skiponempty/37746668#37746668 check this answer – jithin Sep 06 '16 at 04:36

1 Answers1

0

You have to check if $model to be updated had already an image and react accordingly if user has chosen a new image.

Example

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

    $nameImage = $model->name;

    $old_image = $model->bookimg;

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

    //If user has chosen an image
    if (!empty($model->bookimg)) {

        if (!empty($old_image)) {

            //Delete old image from filesystem or/and database
            //...
            //...

        }

        //Save the new image
        $model->bookimg->saveAs('images/'.$nameImage.'.'.$model->bookimg->extension);
        $model->bookimg = 'images/'.$nameImage.'.'.$model->bookimg->extension;
    }

    //Also consider checking if model has been successfully saved before redirect
    $model->save();

    return $this->redirect(['view', 'id' => $model->id]);

} else {
    return $this->render('update', [
        'model' => $model,
    ]);
}
Kostas Mitsarakis
  • 4,772
  • 3
  • 23
  • 37