Yii 2 – Redirect / Reload on krajee DatePicker changeDate event
2016-03-05 – 16:50During my experiments with the Yii2 framework and krajee’s DatePicker widget I wanted to implement a pretty common use-case where the current page reloads with the newly selected date from the DatePicker as a $_GET parameter. It took a few hours to find the correct variant in the bootstrap docs (my initial mistake was to search in the jquery docs). So I am rewriting it here.
This is how I did it:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | // My auto-reloading DatePicker echo "<label class=\"control-label\">My Auto-Reload DatePicker</label>\n"; echo DatePicker::widget([ 'name' => 'auto_reload_date_picker', 'id' => 'auto_reload_date_picker', 'type' => DatePicker::TYPE_COMPONENT_PREPEND, 'value' => Yii::$app->request->get('date'), 'pluginOptions' => [ 'autoclose' => true, 'format' => 'yyyy-mm-dd', ], 'pluginEvents' => [ 'changeDate' => 'function (e){ var date = $("#auto_reload_date_picker").val(); location.href = "/index.php?r=site/my-action&date="+date; }', ] ]); |
I had some trouble finding the correct expression for the contents of “function (e) { ….}”. This works quite well, even when there’s no $_GET parameter given initially. There’s a related question on krajee’s demo page asking for almost the same.
You probably have to adjust “my-action” in the “location.href” assignment.