Answer the question
In order to leave comments, you need to log in
How to update images in Yii2?
Downloading files was easy.
Stopped on replacement of this file. Specifically for this project, it is not critical to delete the uploaded file.
Specifically:
after loading the file, the fileInput field does not have a file, therefore after fileInput it remains empty and when saving a record about the file from the database. is erased.
The input itself does not have a value property by default. How to bypass this problem?
<?= $form->field($model, 'image')->fileInput() ?>
//вариант 1
if ($model->load(Yii::$app->request->post()) && $model->save()) {
$namefile = date("U");
$model->image = UploadedFile::getInstance($model, 'image');
$model->image->saveAs('images/'.$model->image->baseName.'_'.$namefile.'.'.$model->image->extension );
$model->image = 'images/'.$model->image->baseName.'_'.$namefile.'.'.$model->image->extension;
$model->save();
return $this->redirect(['view', 'id' => $model->ID]);
} else {
return $this->render('create', [
'model' => $model,
]);
}
//вариант 2
if ($model->load(Yii::$app->request->post()) && $model->save()) {
//represent the uploaded file as an instance
$namefile = date("U");
$model->image = UploadedFile::getInstance($model, 'image');
//save path to image in db
if($model->image){
$model->image->saveAs('images/'.$model->image->baseName.'_'.$namefile.'.'.$model->image->extension );
$model->image = '/images/' . $model->image->baseName . '.' . $model->image->extension;
}
//save changes in db
$model->save();
//upload image on server
if($model->image){
$model->upload();
}
return $this->redirect(['view', 'id' => $model->ID]);
} else {
return $this->render('update', [
'model' => $model,
]);
}
Answer the question
In order to leave comments, you need to log in
One attribute must contain the name of the file, the other must contain the file itself.
Suppose you have 'imagename' in the database, we hang the string validator on it,
add another attribute to the model, public $file;
we hang the image validator on it and use it in the form, and we pull 'imagename' only if there is something in $_FiLES
video lesson: uploading a photo to yii2
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question