Jaison Mathew
Jaison Mathew

Reputation: 33

Add onchange to input inside template yii2 fileInput

I am using file upload in yii2 with default yii2 fileInput(). The code is:

$form->field($model, 'image', [
       'template' => "<span class='button'>{input}Browse</span><input type='text' placeholder='Include some files' readonly=''>"
       ])->fileInput(['multiple' => false, 'accept' => 'image/* '])->label(false);

Here I use custom template as above. The problem is that {input} generates input field automatically, but I want to add an onchange attribute to this input. Is it possible? Any help would be appreciated. Thanks

Upvotes: 1

Views: 3587

Answers (1)

Gynteniuxas
Gynteniuxas

Reputation: 7093

It is possible to change whatever you want, however, a more reliable and faster way is to use FileInput Widget by Kartik. You'll have to install it first. To do that, write this command in composer or bash command line: composer require "kartik-v/yii2-widget-fileinput": "*" and after install don't forget to use it by writing use kartik\file\FileInput; in your project .php file.

Then you can see all possible plugin events (there are quite a lot of them). The first event described in there is change ("This event is triggered whenever a single file or multiple files are selected in the file input via the file browse button").

To initialize a plugin event, use something like this:

echo $form->field($model, 'attribute', [
    'template' => "<span class='button'>{input}Browse</span><input type='text' placeholder='Include some files' readonly=''>"])->widget(FileInput::classname(),
     [
        'options' => ['multiple' => false, 'accept' => 'image/*'],
        'pluginEvents' => [
            'change' => 'function(event) {
                alert("File changed");
            }'
        ]
    ])->label(false);

Now you can write your JavaScript/jQuery Closure fuction in those lines where alert("File changed"); is located. It is recommended since it provides you with sufficient options to choose from and much faster development.

Upvotes: 1

Related Questions