在null上调用成员函数saveAs()(是否工作skipOnEmpty)

时间:2016-06-10 10:36:36

标签: yii2

我无法在没有上传图片的情况下更新页面。即使我在规则中编写skipOnEmpty它也不起作用。我错了什么?

这是一个控制器

var opt1 = {type: "basic",title: "Teva Noti1",message: "Don't click me!",iconUrl: "icon-phone.png"}
chrome.notifications.create("noti1",opt1,function(notificationId){
    chrome.notifications.onClicked.addListener(function(notificationId){
        alert("test1")
    })
});

var opt2 = {type: "basic",title: "Teva Noti2",message: "Don't click me!!!",iconUrl: "icon-phone.png"}
chrome.notifications.create("noti2",opt2,function(notificationId){
    chrome.notifications.onClicked.addListener(function(notificationId){
        alert("test2")
    })
});

这是一个模型

    if ($model->load(Yii::$app->request->post())){
        //represent the uploaded file as an instance
        $model->imageFile = UploadedFile::getInstance($model, 'imageFile');

        //save path to image in db
        $model->image = '/images/' . $model->imageFile->baseName . '.' . $model->imageFile->extension;
        //save changes in db 
        $model->save();
      //upload image on server
        $model->upload();
 Yii::$app->session->setFlash('success', 
                "Product is successfully updated!");
        return $this->redirect(['view', 'id' => $model->id]);
    } else {
        return $this->render('update', [

            'model' => $model,
        ]);
    }
}

将文件上传到服务器

public function rules()
{
    return [
        [['name', 'category', 'code', 'price', 'availability', 'brand', 'description'], 'required'],
        [['category', 'code', 'availability', 'is_new', 'is_recommended', 'status'], 'integer'],
        [['price'], 'number'],
        [['description'], 'string'],
        [['name','image', 'brand'], 'string', 'max' => 255],
        [['imageFile'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg'],
    ];
}

1 个答案:

答案 0 :(得分:0)

更改您的控制器代码,如下所示:

if ($model->load(Yii::$app->request->post())){
        //represent the uploaded file as an instance
        $model->imageFile = UploadedFile::getInstance($model, 'imageFile');

        //save path to image in db
        if($model->imageFile){
        $model->image = '/images/' . $model->imageFile->baseName . '.' . $model->imageFile->extension;
        }
        //save changes in db 
        $model->save();
      //upload image on server
        if($model->imageFile){
                $model->upload();
            }
 Yii::$app->session->setFlash('success', 
                "Product is successfully updated!");
        return $this->redirect(['view', 'id' => $model->id]);
    } else {
        return $this->render('update', [

            'model' => $model,
        ]);
    }
}

在上传表单中设置隐藏字段,如下所示:

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


    <?= $form->field($model, 'imageFile')->fileInput() ?>
    <?if(!$model->isNewRecord):
            echo Html::activeHiddenInput($model, 'imageFile');
        endif;
    ?>