0
我無法更新頁面沒有上傳image.Even如果我寫skipOnEmpty在規則中不起作用。我錯了什麼?調用成員函數saveAs()null(不工作skipOnEmpty)
這是一個控制器
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'],
];
}
上傳文件到服務器像下面
public function upload()
{
if ($this->validate()) {
$this->imageFile->saveAs('images/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
return true;
} else {
return false;
}
}
非常感謝。它正在工作。但你能解釋爲什麼我們設置隱藏的領域嗎? –
skipOnEmpty在這裏不適用,因爲在更新操作中$ model-> imageFile屬性不會爲空,它將是一個帶有文件名的字符串。$ file仍然是一個只有鍵的數組,如果沒有再次上傳.So檢查是否($ model-> imageFile){}如果上傳實例是隱藏字段更新中的空文件名。 – jithin
你知道,即使沒有隱藏輸入 –