yii2 kartik fileinput multiple loaded files preview

1.8k Views Asked by At

I'm trying to use kartik fileinput for loading multiple files in my form.

I use my Attachment table to save in the db the filename and other fields and I save the files in my filesystem. I usually link the Attachment with Registry table via RegistryAttachment table.

I succefully save the multiple files, but when I load the files for a specific Registry, I want to see them like when I loaded them the firt time.

I'm trying to this using the following code:

Controller action

public function actionLoadMultiple($registryId = NULL){

    $model = new Attachment();

    if(!$registryId){
        $model->files = [];
        $registryId = 6;//For example
        $registry = \app\models\Registry::findOne($registryId);
        $registryAttachments = $registry->attachments;//Find all Attachment record for registryId
        foreach($registryAttachments as $attachment){
            $model->files[$attachment->original_filename] = $attachment->filePath();
        }
    }

    if (Yii::$app->request->isPost) {
        //Loading the files in the model.
        //After I load them, I save them using the model function uploadMultiple
        $model->files = UploadedFile::getInstances($model, 'files');
        $loadedFiles = $model->uploadMultiple();
        if ($loadedFiles) {
            // file is uploaded successfully
            foreach($loadedFiles as $originalFileName=>$fileName){
                $attachment = new Attachment();
                $attachment->section = $model->section?: 'oth';
                $attachment->description = $model->description ?: 'Other';
                $attachment->filename = $fileName;
                $attachment->original_filename =$originalFileName;
                if(!$attachment->save()){
                    $attachment->removeFile();
                    return ['error'=>\Yii::t('app','Error saving attachments to db. Please contact an administrator')];
                }
            }
            return $this->redirect(['index']);
        }
    }

    return $this->render('load_multiple',['model'=>$model]);
}

Model function

public function uploadMultiple(){
    $files = $this->files;
    $section = $this->section ?: '';
    if(!$files){
        return false;
    }

    $fileNameList = [];
    $path = Utility::getAttachmentsBasePath();
    $count = 1;
    foreach ($files as $file) {
        if (!$section) {
            $section = 'oth';
        }

        $filename = \app\models\Attachment::generateFilename($file->name);

        //I set the path to the right folder
        $completePath = $path . '/' . $section . '/' . $filename;
        if (strtoupper(substr(PHP_OS, 0, 3)) === 'WIN') {
            $completePath = str_replace('/', '\\', ($completePath));
        }

        if (!$file->saveAs($completePath)) {
            Yii::error("Error loading file - error code {$file->error}", "upload");
            return ['error' => \Yii::t('app', 'Error saving files. Please contact an administrator')];
        }

        if (isset($fileNameList[$file->name])) {
            $fileNameList[$file->name . '_' . $count] = $filename ;
            $count++;
        } else {
            $fileNameList[$file->name] = $filename;
        }
    }
    return $fileNameList;
}

View load-multiple

<?php

  use yii\widgets\ActiveForm;
  use kartik\file\FileInput;
  use yii\helpers\Html;


   $this->title = Yii::t('app', 'Create Multiple Attachment');
   $initialPreviewAttachmentFile = [];
   $fileInputShowRemove = true;


   if($model->files){
    foreach($model->files as $key=>$file){
     $basePath = Yii::$app->params['attachmentsBasePath'].'/reg';
     $type = \app\models\Attachment::fileInputTypeForUploaded($key);
     $initialPreviewAttachmentFile[] = $file;
     $initialPreviewAttachmentCaption[] = ['caption'=>$key,'type'=>$type,];
   }
  }


  $form = ActiveForm::begin(['enableAjaxValidation' => true,]);




  echo $form->field($model, 'files[]')->widget(FileInput::class, 
    [
        'name' => 'files[]',
        'options' => ['multiple' => true],
        'pluginOptions' => [
     //                'minFileCount' => 1,
            'maxFileCount' => 10,
            'maxFileSize' => Yii::$app->params["attachmentsMaxSize"],
            'initialPreview' => $initialPreviewAttachmentFile ,
            'initialPreviewAsData' => (!empty($initialPreviewAttachmentFile)),
            'initialPreviewConfig' => $initialPreviewAttachmentCaption,
            'fileActionSettings' => [
                'showDownload' => false,
                'showRemove' => true,
            ],
        ],
    ]);
 ?>
<div class="form-group">
<?=
    Html::submitButton(Yii::t('app', 'Save'), [
        'class' => 'btn btn-success save-attachment',
    ])
?>

If the selected Registry has attached 3 files the result is the following:

Trial of multiple file preview .

In this setting, I have the following issues:

  1. I want to see the content of each files, but it doesn't work.
  2. When I load a new file, the widget remove the already loaded files.
  3. The single file remove button doesn't work
1

There are 1 best solutions below

1
Максат Жанат On

When I load a new file, the widget remove the already loaded files. works only with ajax loading