Answer the question
In order to leave comments, you need to log in
How to organize post update with FileInput widget from Kartik in Yii2?
Hello, I'm using the FileInput widget to upload thumbnails to a post. Creating/editing/etc entries is done with CRUD.
The fact is that when the record update form is loaded, the image name in the database is not loaded, unlike other fields.
Let's say the image and all other fields are filled in and we decide to edit the blocks field .
1. Go to post editing.
2. Replace the contents of the blocks field.
3. Save.
Since the thumbnail field is empty -- it will store null instead of the current content.
Actually, I want to solve this problem. So far, from the options, make a separate function for updating / adding / deleting a thumbnail, but this is already an extreme option. I hope someone has come across this problem and I hope they can help me.
Here is the part of the code that is responsible for displaying the image upload form:
<?= $form->field($model, 'miniature')->widget(FileInput::classname(), [
'options' => ['accept' => 'image/*'],
]); ?>
public function beforeSave($insert)
{
if ($file = UploadedFile::getInstance($this, 'miniature') ){
$dir = Yii::getAlias('@frontend').'/web/upload/';
$this->miniature = time().'.'.$file->extension;
$file->saveAs($dir.$this->miniature);
}
return parent::beforeSave($insert);
}
Answer the question
In order to leave comments, you need to log in
Good evening.
I think beforeSave() is a bad idea to save the image.
Better check if miniature is empty or not. If not empty, then fill in the new data with the old value. Of course, provided that you did not transfer a new value.
Something like this should be
public function beforeSave($insert)
{
if(!$this->isNewRecord && self::getOldAttribute('miniature') != ''){
$this->miniature = self::getOldAttribute('miniature');
}
return parent::beforeSave($insert);
}
<?= $form->field($model, 'miniature')->widget(FileInput::classname(), [
'options' => ['accept' => 'image/*'],
'model' => !Yii::$app->isNewRecord ? $model->miniature : null
]); ?>
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question