Yii2: Combining Kartik's FileInput & Kartik's DetailView

686 views Asked by At

I'm trying single-file uploads using Kartik's FileInput.

Things go fine when doing this through standard create form as the following returns non-null:

$filedata = UploadedFile::getInstance($model, 'filedata'); 

However it always returns null when going into Kartik's DetailView in edit mode and trying to update the file.

In view.php I have:

[
    'attribute' => 'filedata',
    'visible' => Yii::$app->user->can('doIt'),
    'type' => DetailView::INPUT_FILEINPUT,
    'rowOptions' => ['class' => 'kv-view-hidden'],
    'widgetOptions' => ['options' => ['accept' => 'application/pdf'],
    'pluginOptions' => [
        'showUpload' => false,
        'allowedFileExtensions' => ['pdf'],
        'initialCaption' => $model->filename,
    ],
    'pluginEvents' => [
        'filecleared' => <whatever>,
        'fileloaded'  => <whatever>,
    ],
  ],
],   

while in _form.php (which does work):

<?php $form = ActiveForm::begin(['options' => ['enctype' => 'multipart/form-data']]); ?>

    <?= $form->field($model, 'filedata')->widget(FileInput::classname(), [
        'options' => ['accept' => 'application/pdf'],
        'pluginOptions' => [
            'showUpload' => false,
            'allowedFileExtensions' => ['pdf'],
            'initialCaption' => $model->getOldAttribute('filename'),
        ],
        'pluginEvents' => [
            'filecleared' => <whatever>,
            'fileloaded'  => <whatever>,
        ],
    ]) 
?>

Any ideas? (BTW, don't know whether 'multipart/form-data' is needed somehow in view.php as it is in _form.php, so anyone confirming this and giving some details should be welcome).

1

There are 1 answers

0
Antonio López On BEST ANSWER

Of course, multipart/form-data is needed both in _form.php and view.php as well, as follows:

'formOptions' => ['options' => ['enctype' => 'multipart/form-data']],
'attributes' => [
...
[
    'attribute' => 'filedata',
    'visible' => Yii::$app->user->can('doIt'),
    'type' => DetailView::INPUT_FILEINPUT,
    'rowOptions' => ['class' => 'kv-view-hidden'],
    'widgetOptions' => ['options' => ['accept' => 'application/pdf'],
    'pluginOptions' => [
        'showUpload' => false,
        'allowedFileExtensions' => ['pdf'],
        'initialCaption' => $model->filename,
    ],
    'pluginEvents' => [
        'filecleared' => <whatever>,
        'fileloaded'  => <whatever>,
    ],
  ],
],
....
]