Javascript In Yii 2.0

I am starting my first project with Yii2.0, and I realized that I can not add Javascript the way that I was use to.

What I want to do is simple add a datepicket to an input field at the moment of creating a model.

Anyone is using datepickers or an otehr javscript that is only needed in one view ? Will be really great if someone helps me with this.

you can register it in ur view like this

$this -> registerJsFile( '');

where first parameter is the name of the js file you want to register. for more details please read here

Use registerJsFile() to add a file to a page and registerJs() to output inline script code.

So your code can look like this, for example:


// edit.php

$this->registerJsFile('/path/to/file.js', ['yii\web\JqueryAsset']);


Sorry for the late response. I just started to explore v2,0 yesterday.

If you need datepickers, and, maybe, another jquery UI’s check out this link -

And my personal thoughts - default look is ugly, configure it by using this code:

    <?= $form




            ['template' => "{label}\n<div class=\"col-lg-2\">{input}</div>\n<div class=\"col-lg-8\">{error}</div>",]





            'clientOptions' => ['dateFormat' => 'yy-mm-dd']]

        ); ?>

Source: here

So methods have been shifted to view class. See registerJs for example

You have to read Guide especially on upgrading to Yii2!

Thanks everyone, I will read the guide :).

For now I will try to use registerJS and come back here :).

I will try the jui librray too, I think that it will help me for more stuff :)

Thanks again !


I did it in 2 different ways.

The asset manager and the reisterJs functions. Both work great. Thanks for the advice.

Anyway I am trying to use the datepicker of bootstrap and it seems that it does not find the function. When I fix it I will come back with the full solution.


for now I will be using registeJS due that is really a little JS needed for the datepicker.

I am using the following library for the datepicker ->

In the form, the textinput where I want to put the date, I add an ID for later use as followin:

  <?= $form->field($model, 'fechaCreacion')->textInput(['id' => 'date-fechaCreacion']) ?>

Then I just create the code for attaching the event :

       $js = '$( "#date-fechaCreacion" ).datepicker()';

       $this->registerJs($js, $this::POS_END);

About the JS Library, I am including it inside an AssetBundle :

   public $basePath = '@webroot';

    public $baseUrl = '@web';

    public $css = [



    public $js = [




    public $depends = [








And that is all for now. I hope that if someone had the same issue, could fix it like this :).