问题
I can't update a page without of upload image.Even if I write skipOnEmpty in the rules it doesn't work . What do I wrong?
This is a controller
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,
]);
}
}
This is a 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'],
];
}
uploading of a file to the server
public function upload()
{
if ($this->validate()) {
$this->imageFile->saveAs('images/' . $this->imageFile->baseName . '.' . $this->imageFile->extension);
return true;
} else {
return false;
}
}
回答1:
change your controller code like below:
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,
]);
}
}
Set a hidden field in your upload form like below:
<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>
<?= $form->field($model, 'imageFile')->fileInput() ?>
<?if(!$model->isNewRecord):
echo Html::activeHiddenInput($model, 'imageFile');
endif;
?>
来源:https://stackoverflow.com/questions/37746082/call-to-a-member-function-saveas-on-nulldoest-work-skiponempty