Problem with fileInput() default value

(SomebodyHere) #1

I’m trying to make a form to edit some fields, one of which is a file input:

<?= $form->field($model, 'image')->fileInput() ?>

At this point the user has already uploaded an image, and doesn’t need to change the original one unless s/he wants to.

Problem is, I can’t seem to find a way to prefill the fileInput() field with the image the user first uploaded.

My controller has:

            if ($model->load(Yii::$app->request->post()))
                $model->image = UploadedFile::getInstance($model, 'image');

                if ($model->editPointImage()) {
                $get = [Table]::findOne($id);
                $model->image = $get->image;

I looked up several threads (Form with FileInput and update action, Fileinput() Defaults To 'no File Chosen') and tried the following:

            if ($action == 'edit')
                echo "<img src = $model->image />";
        <?= $form->field($model, 'image')->fileInput() ?>

as well as

<?= $form->field($model, 'image')->fileInput(['value' => $path]) ?>

but to no avail.

I have checked the console CTRL+Shift+I in Chrome and the value for the input is correct; the form still isn’t working.

I also tried to remove the required constraint from the image field, but am still asked to upload a file when submitting the form without one.

Does anyone know of a solution? Thanks!

(Anil Chaudhari) #2

Hi @SomebodyHere, What does the $path contains?
As far as I know, fileInput doesn’t support prefilled values like textInput and others.

You can use scenarios to set the model’s rules for different purposes.

and before uploading the image you can check whether UploadedFile instance is available or not

$imagepath = $model->image;    
$model->image = UploadedFile::getInstance($model, 'image');
if ($model->image) {
    // image upload code
} else {
    $model->image = $imagepath;

(SomebodyHere) #3

@imanilchaudhari $path is the path to the original file.

I also discovered that although I removed the required restraint I failed to remove the 'skipOnEmpty' => false.

Hmm that is strange because it’s still showing up in my console value = $path

(Tomasz Kane) #4

I usually add “when” argument to “required” validator:

[‘image’, ‘required’, ‘when’ => function($model) { return $model->getIsNewRecord(); }]

(SomebodyHere) #5

Ahh, thanks for the tip!