M
M
Mark2017-07-05 20:49:30
Yii
Mark, 2017-07-05 20:49:30

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.
oH1J5.jpg
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/*'],
]); ?>

The function to save the image in the model:
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

1 answer(s)
D
Dmitry, 2017-07-05
@MarkLb

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); 
}

This is the first thing that came to mind. And so, it is necessary to deal with the documentation of the widget, perhaps it is provided there.
It might be something like this, but I'm not sure.
<?= $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 question

Ask a Question

731 491 924 answers to any question