在null上调用成员函数saveAs()(如果我不选择图像,则无法更新)

时间:2016-09-05 21:58:15

标签: yii2 yii2-validation

如果我不选择图片,则无法更新。我错过了什么错误?

这是一个控制器:

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,
        ]);
    }

这是一个模型:

[['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']],

这是一种形式:

<?= $form->field($model, 'bookimg')->fileInput()->label('Book Cover') ?>

1 个答案:

答案 0 :(得分:0)

如果用户选择了新图片,您必须检查要更新的$model是否已有图像,并做出相应的反应。

示例

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,
    ]);
}