Fileinput issue in ActiveForm when updating via Yii 2

471 views Asked by At

I am using Yii2 framwork. My file upload function worked well when I upload a single img, while when I click the posed article and I only want to update the post again(Suppose I didn't want to update the img, I only want to update other contents). But I found my uploaded file were replaced with an empty value(varchar type) when I click view. my uploaded img can't show out.

I do tried to fixed by myself as below, But the existing file value can't be saved when I click the submit button.

                <?php

                    if (($post->file) != "") {
                    echo $form->field($post, 'file')->textInput()->hint('My currently uploaded file')->label('My Photo') ;

                }
                else{
                    echo $form->field($post, 'file')->fileInput()->hint('To upload a new file')->label('My Photo') ;
                }

                ?>

When I click submit button, my existing file was gone. Is there any good way to fix it. Thanks for your opinions in advance.

2

There are 2 answers

3
Araz Jafaripur On BEST ANSWER

Use another variable in your model for upload a file.

For example use file_field name for get file from submitted and store in file field.

class PostModel extends Model
{

    /**
     *
     * @var UploadedFile
     */
    public $file_field;
    
    public function rules() {
        return [
            ['file_field', 'file'],
        ];
    }
}
echo $form->field($post, 'file_field')->fileInput()->hint('To upload a new file')->label('My Photo') ;
$post->file_field = UploadedFile::getInstance($post, 'file_field');

For upload new file check the file_field:

if ($post->file_field) {
    // $post->file  old file
    // Save $post->file_field and store name in $post->file
}
1
WeSee On

Add a rule to your model rules:

[['file'], 'file', 'skipOnEmpty' => true, 'extensions' => 'png, jpg'],

and check for an empty upload in your controller:

if (Yii::$app->request->isPost) {
    $ok = true;
    // process your other fields...
    ...
    // process image file only if there is one
    $post->file= UploadedFile::getInstance($post, 'file');
    if ($post->file && $post->upload()) {
        
    }
    if ($ok) {
        return $this->redirect(...);
    }
}

See Yii2 docs and the Yii2 guide for detailed infos about file upload.