B
B
BarakudaX7772019-06-08 14:59:43
Yii
BarakudaX777, 2019-06-08 14:59:43

Question on YII2. Why is the fileinput field empty when opening the edit form?

Good afternoon.
I'm making a simple form with file upload and file information. For fileinput I use a widget from kartik.
Understood the file upload. After uploading the file to the variable file, I put the file name.
The problem is that when I try to change the entries in the form, the fileinput field is empty and I need to upload the file again. How to fix it? Maybe I need again the file field in which only the file name is stored in the database to lead to the full path to the file?
The code was not posted in full, unrelated entries were removed so as not to burden perception.
I post the implementation code:

Model InvoicesFile
public function rules()
    {
        return [
            [['iid', 'itype', 'name'], 'required'],
            [['iid'], 'integer'],
            [['itype'], 'string'],
      [['file'], 'file'],
            [['name'], 'string', 'max' => 150],
        ];
    }

    public function attributeLabels()
    {
        return [
            'id' => 'ID',
            'iid' => 'Счет',
            'itype' => 'Вид файла',
            'file' => 'Ссылка на файл',
            'name' => 'Заголовок',
        ];
    }
public function beforeSave($insert) {
    if ($insert) {
      $this->itype='invoice';
    }
    return parent::beforeSave($insert);
  }

Display (view)
<?php

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

/* @var $this yii\web\View */
/* @var $model common\models\InvoicesFiles */
/* @var $form yii\widgets\ActiveForm */
?>

<div class="box box-primary">
    <div class="box-body">
    <?php $form = ActiveForm::begin(['id'=>'form_invoice_file','type' => ActiveForm::TYPE_INLINE ,'options' => ['enctype' => 'multipart/form-data']]);?>
    <?=$form->errorSummary($model);?>
    <div class='row'>
      <div class='col-md-6'>
        <?=$form->field($model, 'iid')->widget(Select2::classname(), [
          'data' => Yii::$app->MyFunctions->InvoicesArray(),
          'options' => ['placeholder' => 'Выберите счет','id'=>'invoices-selector'],			
          'pluginOptions' => [
            'allowClear' => true,	
          ]
          
        ]);?>
      </div>
      <div class='col-md-6'>
        <?= $form->field($model, 'name')->textInput(['maxlength' => true,'style'=>'width:100%']) ?>
      </div>
    </div>
    <div class='row'>
      <div class='col-md-6'>
        <?=$form->field($model, 'itype')->widget(Select2::classname(), [
          'data' => $model->typesArray,
          'language' => 'ru',
          'options' => ['placeholder' => 'Вид файла','id'=>'filetype-selector'],
          'pluginOptions' => [
            'allowClear' => true,						
            'width' => '100%'
          ]
        ]);?>
      </div><?=$model->file;?>
      <div class='col-md-6'>
        <?php echo $form->field($model, 'file')->fileInput(); ?>
        <?php  $form->field($model, 'file')->widget(FileInput::classname(), [
          'showMessage' => true,
          'pluginOptions' => [
            'showPreview' => false,
            'showCaption' => true,
            'showRemove' => true,
            'showUpload' => false,
            'maxFileSize'=>30720,
          ]]
        );?>
      </div>
    </div>
    <div class="box-footer">
      <?= Html::submitButton('Сохранить', ['class' => 'btn btn-primary btn-flat']) ?>
    </div>
    
    <!-- /.box-footer-->
    <?php ActiveForm::end(); ?>
</div>

Well, the controller:
namespace backend\controllers;

use Yii;
use common\models\InvoicesFiles;
use common\models\InvoicesFilesSearch;
use yii\web\Controller;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use yii\web\UploadedFile;

    public function actionCreate()
    {
        $model = new InvoicesFiles();
        if ($model->load(Yii::$app->request->post()) && $model->save()) {
      
      //Загрузка файла
      if($model->file = UploadedFile::getInstance($model,'file')){
        //Сохранение файла
        $uploadPath = Yii::getAlias('@frontend/web/uploads/invoices/'.$model->iid.'/');
        if (!file_exists($uploadPath)) { 
          mkdir($uploadPath, 0755, true);
        }
        $filename = $model->file->baseName.'.'.$model->file->extension;
        if(file_exists($uploadPath.$filename)){unlink($uploadPath.$filename);}
        $model->file->saveAs($uploadPath.$filename);
        $model->file =$filename;
        $model->save();
      }			
      return $this->redirect(['view', 'id' => $model->id]);
        }
    
        return $this->render('create', [
            'model' => $model,
        ]);
    }

    public function actionUpdate($id)
    {
        $model = $this->findModel($id);

        if ($model->load(Yii::$app->request->post()) && $model->save()) {
      
      //Загрузка файла
      if($model->file = UploadedFile::getInstance($model,'file')){
        //Сохранение файла
        $uploadPath = Yii::getAlias('@frontend/web/uploads/invoices/'.$model->iid.'/');
        if (!file_exists($uploadPath)) { 
          mkdir($uploadPath, 0755, true);
        }
        $filename = $model->file->baseName.'.'.$model->file->extension;
        if(file_exists($uploadPath.$filename)){unlink($uploadPath.$filename);}
        $model->file->saveAs($uploadPath.$filename);
        $model->file =$filename;
        $model->save();
      }			
      
            return $this->redirect(['view', 'id' => $model->id]);
        }

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

Answer the question

In order to leave comments, you need to log in

[[+comments_count]] answer(s)
D
Dmitry, 2019-06-08
@slo_nik

Good afternoon.
To do this, you need to create a couple of methods in the model and add some settings to the widget itself.
The official site has an example with settings on how to do this. See the output of the widget with two images, and the code is just below.
It is necessary to set the following parameters in "pluginOptions":
1) initialPreview
2) initialPreviewAsData
3) initialPreviewConfig
4) overwriteInitial The
method in the model may look like this:

public function getImagesLinks()
    {
        $path = ArrayHelper::getColumn(self::find()->all(), 'pathImg');
        return $path;
    }

    public function getImagesLinksData()
    {
        $files = UploadsFiles::find()->all();
        return ArrayHelper::toArray($files,[
            UploadsFiles::class => [
                'caption' => 'file',
                'key' => 'id'
            ]
        ]);
    }

The field with the widget itself will be like this:
echo $form->field($model, 'imagesFile')->widget(FileInput::class, [
    'options' => ['accept' => 'image/*', 'multiple' => true],
    'pluginOptions' => [
        'showUpload' => false,
        'showRemove' => false,
        'overwriteInitial'=>false,
        'initialPreviewAsData' => true,
        'initialPreview' => $model->imagesLinks,
        'initialPreviewConfig' => $model->imagesLinksData,
        'uploadUrl' => Url::to(['upload-img']),
        'deleteUrl' => Url::to(['delete-img']),
    ]
])->label('<h3>Test Img</h3>');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question