Giter Site home page Giter Site logo

kartik-v / yii2-datecontrol Goto Github PK

View Code? Open in Web Editor NEW
55.0 11.0 29.0 225 KB

Date control module allowing separation of date formats for View & Model for Yii Framework 2.0.

Home Page: http://demos.krajee.com/datecontrol

License: Other

PHP 90.61% JavaScript 9.39%

yii2-datecontrol's Introduction

Krajee Logo
yii2-datecontrol
Donate       kartikv

Stable Version Untable Version License Total Downloads Monthly Downloads Daily Downloads

The Date Control module allows controlling date formats of attributes separately for View and Model for Yii Framework 2.0. It thus allows an easy way to work with dates when displaying to users in one way (format / timezone) but saving it in the database in another way (format / timezone).

Refer CHANGE LOG for details on changes to various releases.

NOTE: Version 1.9.5 has BC breaking changes. A new property widgetOptions is available. This property will replace the options property for the scenario when autoWidget or widgetClass is set.

Why Date Control?

When working with the great Yii Framework, one of the most common observations I had was the need to have a proper control on the date settings. The date settings for each Yii application, are unique to each application and region. Most Yii developers or users almost always need an option of displaying date and time in ONE specific format, but save them to database in ANOTHER format. So to summarize, the problem statement was:

  • Lack of a single configuration method to display date & times to user (or VIEW) in ONE format
  • Lack of a configuration method to save date & times in database (or MODEL) in ANOTHER format

Most existing Yii solutions try to overcome the above by setting the format in model->afterFind, present in view, then unformat it in model->setAttribues or model->beforeValidate. This was still an issue when one had many models and views in the application and changes in development cycle, had to be replicated in many places (more complex scenarios being multi-regional formats).

This module helps overcome this large gap by addressing all of these at the presentational level. The module enables one to configure the date and time settings separately for DISPLAY and SAVE. This can be setup either globally or individually at each DateControl widget level. And if this is not useful enough, it automatically enables any date/time picker widgets to be used in conjunction with this.

How this magic works, is that the extension just alters this at the presentational layer (VIEW). It automatically sets the base model input to hidden and displays a mirror input in the display format one has set. Then on each edit of the display input, the extension traps the change event, and overrwrites the hidden base model input as per the desired save format. The other good thing is, that the extension automatically triggers the javascript change event for the base model input as well. Thus all client model validations and other jquery events needed by Picker widgets are automatically triggered.

NOTE: All date and time formats used across this module follow one standard - i.e. PHP Date Time format strings. The extension automatically provides three widgets to display and control the date-time inputs.

Module

The extension has been created as a module to enable access to global settings for your application. In addition, it allows you to read and format date times between client and server using PHP DateTime object. The DateControl widget uses ajax processing to convert display (view) format to model (save) format.

use kartik\datecontrol\Module;
'modules' => [
   'datecontrol' =>  [
        'class' => 'kartik\datecontrol\Module',
        
        // format settings for displaying each date attribute (ICU format example)
        'displaySettings' => [
            Module::FORMAT_DATE => 'dd-MM-yyyy',
            Module::FORMAT_TIME => 'HH:mm:ss a',
            Module::FORMAT_DATETIME => 'dd-MM-yyyy HH:mm:ss a', 
        ],
    
        // format settings for saving each date attribute (PHP format example)
        'saveSettings' => [
            Module::FORMAT_DATE => 'php:U', // saves as unix timestamp
            Module::FORMAT_TIME => 'php:H:i:s',
            Module::FORMAT_DATETIME => 'php:Y-m-d H:i:s',
        ],
    
        // set your display timezone
        'displayTimezone' => 'Asia/Kolkata',

        // set your timezone for date saved to db
        'saveTimezone' => 'UTC',
        
        // automatically use kartik\widgets for each of the above formats
        'autoWidget' => true,
        
        // use ajax conversion for processing dates from display format to save format.
        'ajaxConversion' => true,

        // default settings for each widget from kartik\widgets used when autoWidget is true
        'autoWidgetSettings' => [
            Module::FORMAT_DATE => ['type'=>2, 'pluginOptions'=>['autoclose'=>true]], // example
            Module::FORMAT_DATETIME => [], // setup if needed
            Module::FORMAT_TIME => [], // setup if needed
        ],
        
        // custom widget settings that will be used to render the date input instead of kartik\widgets,
        // this will be used when autoWidget is set to false at module or widget level.
        'widgetSettings' => [
            Module::FORMAT_DATE => [
                'class' => 'yii\jui\DatePicker', // example
                'options' => [
                    'dateFormat' => 'php:d-M-Y',
                    'options' => ['class'=>'form-control'],
                ]
            ]
        ]
        // other settings
    ]
];

Params Configuration

The extension allows configuration of dateControlDisplay and dateControlSave settings at Yii application params level. The params configuration will override the settings at the module level. This configuration is useful when one wants to dynamically change these params settings at runtime. The settings can be overridden at DateControl widget level.

Refer the defaulting rules documentation for details.

DateControl

The main widget for rendering each date control on your views. Many settings will be defaulted from the module setup, but can be overridden at the widget level. An usage example with ActiveForm and using \kartik\widgets\DateTimePicker is shown below. Note you can pass date-time formats as supported by ICU or PHP. To set a PHP date time format - prepend the format string with php: as shown below.

echo $form->field($model, 'datetime_2')->widget(DateControl::classname(), [
    'displayFormat' => 'php:d-M-Y H:i:s',
    'type'=>DateControl::FORMAT_DATETIME
]);

NOTE: With version v1.2.0 this extension can use the new Krajee jQuery library php-date-formatter to perform client side date format conversion instead of using ajax, for basic date formats (without timezone). The extension can thus now easily read date & time stamps consistently in ONE format (PHP DateTime) across the client and server. However, it is recommended to use ajaxConversion if you need seamless integration with PHP DateTime functions like timezone support.

Demo

You can see detailed documentation and usage, a detailed demo and API Code Documentation for the extension.

Installation

The preferred way to install this extension is through composer.

Note: Check the composer.json for this extension's requirements and dependencies. Read this web tip /wiki on setting the minimum-stability settings for your application's composer.json.

Either run

$ php composer.phar require kartik-v/yii2-datecontrol "@dev"

or add

"kartik-v/yii2-datecontrol": "@dev"

to the require section of your composer.json file.

Usage

use kartik\datecontrol\Module;
use kartik\datecontrol\DateControl;

License

yii2-datecontrol is released under the BSD 3-Clause License. See the bundled LICENSE.md for details.

yii2-datecontrol's People

Contributors

educationisenemy avatar enrica-r avatar gael-wogenstahl avatar kartik-v avatar nsanden avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

yii2-datecontrol's Issues

Probably bug re triggering of change event in datecontrol.js

When using asynchronous $.ajax the success function that alters the value of $idSave on line 73 is being called after the call to trigger the change event on line 91 resulting in the change event not having access to the new value - because of its asynchronous-ness :)

To fix I suggest putting $idSave.trigger('change'); following $idSave.val() calls on line 55 and 73 in the current code (instead of line 91 after the call to validate).

Note this fix also resolves an issue with on change being called three times for save input instead of once - didn't trace thru to find why. I havn't tested any other scenarios other than my own use so haven't created a PR but can if you like - in other.

Hope I have this right and am not wasting your time.

Error by defining widgetSettings in modul config

When defining the datepicker class in widgetSettings (autoWidget false) I get an Error from Yii as following:

 PHP Warning – yii\base\ErrorException
htmlspecialchars() expects parameter 1 to be string, array given

    1. in C:\xampp\htdocs\yii2\TestApp4\vendor\yiisoft\yii2\helpers\BaseHtml.php at line 95
    8687888990919293949596979899100101102103104

         * @param string $content the content to be encoded
         * @param boolean $doubleEncode whether to encode HTML entities in `$content`. If false,
         * HTML entities in `$content` will not be further encoded.
         * @return string the encoded content
         * @see decode()
         * @see http://www.php.net/manual/en/function.htmlspecialchars.php
         */
        public static function encode($content, $doubleEncode = true)
        {
            return htmlspecialchars($content, ENT_QUOTES | ENT_SUBSTITUTE, Yii::$app->charset, $doubleEncode);
        }

        /**
         * Decodes special HTML entities back to the corresponding characters.
         * This is the opposite of [[encode()]].
         * @param string $content the content to be decoded
         * @return string the decoded content
         * @see encode()
         * @see http://www.php.net/manual/en/function.htmlspecialchars-decode.php

    2. in C:\xampp\htdocs\yii2\TestApp4\vendor\yiisoft\yii2\helpers\BaseHtml.php – yii\helpers\BaseHtml::encode() at line 1623
    3. in C:\xampp\htdocs\yii2\TestApp4\vendor\yiisoft\yii2\helpers\BaseHtml.php – yii\helpers\BaseHtml::renderTagAttributes() at line 131
    4. in C:\xampp\htdocs\yii2\TestApp4\vendor\yiisoft\yii2\helpers\BaseHtml.php – yii\helpers\BaseHtml::tag() at line 480
    5. in C:\xampp\htdocs\yii2\TestApp4\vendor\yiisoft\yii2\helpers\BaseHtml.php – yii\helpers\BaseHtml::input() at line 542
    6. in C:\xampp\htdocs\yii2\TestApp4\vendor\kartik-v\yii2-datecontrol\datecontrol\DateControl.php – yii\helpers\BaseHtml::textInput() at line 190
    184185186187188189190191192193194195196

        {
            $value = empty($this->value) ? '' : $this->getDisplayValue($this->value);
            if (!$this->isWidget()) {
                if (empty($this->options['class'])) {
                    $this->options['class'] = 'form-control';
                }
                return Html::textInput($this->_displayAttribName, $value, $this->options);
            }
            $class = (!$this->autoWidget && !empty($this->widgetClass)) ? $this->widgetClass :
                ArrayHelper::getValue($this->_widgetSettings[$this->type], 'class', '\yii\jui\DatePicker');

            if (!empty($this->displayFormat) && $this->autoWidget) {
                $this->options = ArrayHelper::merge(Module::defaultWidgetOptions($this->type, $this->displayFormat), $this->options);

    7. in C:\xampp\htdocs\yii2\TestApp4\vendor\kartik-v\yii2-datecontrol\datecontrol\DateControl.php – kartik\datecontrol\DateControl::getDisplayInput()

If found out that if (!$this->isWidget()) { in getDisplayInputis true even if a widget class is defined in _widgetSettings from modul.

$class = (!$this->autoWidget && !empty($this->widgetClass)) ? $this->widgetClass : ArrayHelper::getValue($this->_widgetSettings[$this->type], 'class', '\yii\jui\DatePicker'); comes too late and makes no sense. $this->widgetClass is never filled in. But $this->isWidget checks this variable. If it would be filled in earlier then mentioned check makes no sense because widgetClasswill never be empty at this point.
debug_getdisplayinput

The debug screenshot shows that HTML::textInput()is called with wrong options.

Saving a datetime value is not working

I set up the following config in params:

 // format settings for displaying each date attribute (ICU format example)
  'displaySettings' => [
        Module::FORMAT_DATE => 'dd-MM-yyyy',
        Module::FORMAT_TIME => 'HH:mm:ss a',
        Module::FORMAT_DATETIME => 'dd.MM.yyyy HH:mm:ss', 
    ],

    // format settings for saving each date attribute (PHP format example)
    'saveSettings' => [
        Module::FORMAT_DATE => 'yyyy-MM-dd', // saves as unix timestamp
        Module::FORMAT_TIME => 'HH:mm:ss',
        Module::FORMAT_DATETIME => 'yyyy-MM-dd HH:mm:ss',  //I also tried php:Y-m-d H:i:s
    ],
  'displayTimezone' => 'UTC',
        // set your timezone for date saved to db
        'saveTimezone' => 'UTC',

in _form-view, I use

$form->field($model, 'start')->widget(DateControl::classname(), [
    'type' => DateControl::FORMAT_DATETIME
]);

But the post result does not contain the time:
Event [
'title' => '...'
'start' => '2015-02-12 00:00:00'
'end' => ''
'type' => '10'
]
start-event-start '12.02.2015 11:00:57'

autoWidgetSettings for DatePicker

In the example config there is following configuration for the DatePicker widget:

'pluginOptions'=>['autoClose'=>true]

There should be "autoclose" in small caps instead:

'pluginOptions'=>['autoclose'=>true]

display wrong

when i config:

    ['attribute'=>'check_in_time','format'=>['datetime',(isset(Yii::$app->modules['datecontrol']['displaySettings']['datetime'])) ? Yii::$app->modules['datecontrol']['displaySettings']['datetime'] : 'd-m-Y H:i:s A']],
    ['attribute'=>'check_out_time','format'=>['datetime',(isset(Yii::$app->modules['datecontrol']['displaySettings']['datetime'])) ? Yii::$app->modules['datecontrol']['displaySettings']['datetime'] : 'd-m-Y H:i:s A']],

in grid view, and it displays: 9-4-2014 0:: 9-7-2014 0::

Ajax Convertion not supporting locales

Seems that DateTime::createFromFormat, used at ParseController::actionConvert() doesn't take LC_TIME in consideration.

So when displaying a widget with a displayFormat like php:d / F / Y (fulltext month) and a saveFormat like php:d-m-Y, the conversion will fail because PHP cant find the month name for languages other then 'en'.

I could fix it by replacing the code using DateTime::createFromFormat:

if ($dispTimezone != null) {
    $date = DateTime::createFromFormat($dispFormat, $dispDate, new DateTimeZone($dispTimezone));
} else {
    $date = DateTime::createFromFormat($dispFormat, $dispDate);
}

with:

$fmt = new \IntlDateFormatter(Yii::$app->formatter->locale, \IntlDateFormatter::FULL, \IntlDateFormatter::FULL);
$fmt->setPattern(FormatConverter::convertDatePhpToIcu($dispFormat));
$fmt->setTimezone($dispTimezone);
$date = new DateTime();
$date->setTimestamp($fmt->parse($dispDate));

datecontrol is not working

with this setting
'datecontrol' => [
'class' => 'kartik\datecontrol\Module',

    // format settings for displaying each date attribute (ICU format example)
    'displaySettings' => [
        Module::FORMAT_DATE => 'dd-MM-yyyy',
        Module::FORMAT_TIME => 'HH:mm:ss a',
        Module::FORMAT_DATETIME => 'dd-MM-yyyy HH:mm:ss a', 
    ],

    // format settings for saving each date attribute (PHP format example)
    'saveSettings' => [
        Module::FORMAT_DATE => 'yyyy-mm-d', // saves as unix timestamp
        Module::FORMAT_TIME => 'php:H:i:s',
        Module::FORMAT_DATETIME => 'php:Y-m-d H:i:s',
    ],

    // set your display timezone
    //'displayTimezone' => 'Asia/Kolkata',

    // set your timezone for date saved to db
   // 'saveTimezone' => 'UTC',

    // automatically use kartik\widgets for each of the above formats
    //'autoWidget' => true,

    // default settings for each widget from kartik\widgets used when autoWidget is true
    'autoWidgetSettings' => [
        Module::FORMAT_DATE => ['type'=>2, 'pluginOptions'=>['autoclose'=>true]], // example
        Module::FORMAT_DATETIME => [], // setup if needed
        Module::FORMAT_TIME => [], // setup if needed
    ],

    // custom widget settings that will be used to render the date input instead of kartik\widgets,
    // this will be used when autoWidget is set to false at module or widget level.
    'widgetSettings' => [
        Module::FORMAT_DATE => [
            'class' => 'yii\jui\DatePicker', // example
            'options' => [
                'dateFormat' => 'php:d-M-Y',
                'options' => ['class'=>'form-control'],
            ]
        ]
    ]
    // other settings
]

and in form
field($model, 'dob')->widget(DateControl::classname(), [ 'type'=>DateControl::FORMAT_DATE, 'ajaxConversion'=>false, 'options' => [ 'pluginOptions' => [ 'autoclose' => true ] ] ]);?>

it is not saving to database and if i change in format then calender is not showing

Enh: Javascript enhancement

Hello Kartik,
I created a fork and have extended your datacontrol extension with following functionality:

  • Javascript enhancement with parser, date enhancer (explained later) and date formatter instead of ajax call (this is still possible). It works faster.
  • JS is working with dates, times and datetimes automatically.
  • Jquery function encapsulated as normal Jquery plugin with $.each. Datecontrol could be bind to a class. The hash key is also stored as data-datecontrol-obj at input control. The function read this alternatively.
  • Datecontrol reads international translations for month and day from intl (if loaded and language isn't en) and send this to $.fn.datecontrol.defaults which is used by JS.
  • I built in a date enhancer. What is the meaning. If you enter eg. "20" the enhancer is creating "20-07-2014" or eg. "2008" --> "20-08-2014". It analyzes the content, checks the target format an interpretes the content as date. So "2.8" --> "02-08-2014" or "2008.5" --> "20-08-2015". The separator for input is irrelevant, for output it is taken from DispFormat. The enhancer works only if 'pluginOptions' => [ 'keyboardNavigation' => false, 'forceParse' => false] is predifined.
  • The key up and key down increases rsp, decreases the date one day.

If you are interested to see and check it I could sent it to you. Tell me if I should do a fork and a PR.
Regards,
Enrica R.

Wrong date display, only from 00:00 to 00:59 am

Hi Kartik, excuse me, but i don't know how solve this problem.
I'm using your extension and it works fine.
I configure params.php in this way:
...
'dateControlDisplay' => [
Module::FORMAT_DATE => 'php:d/m/Y',
Module::FORMAT_TIME => 'php:H:i:s',
Module::FORMAT_DATETIME => 'php:d/m/Y H:i:s',
],
'dateControlSave' => [
Module::FORMAT_DATE => 'php:Y-m-d',
Module::FORMAT_TIME => 'php:H:i:s',
Module::FORMAT_DATETIME => 'php:Y-m-d H:i:s',
],

            'dateControlDisplayTimezone'=>  'Europe/Rome',
            'dateControlSaveTimezone'=>  'Europe/Rome',

...

but only from 00:00 to 00:59 am (my pc hour) there is an error and the convertion add 1 day to the date in the database .

For example in the database i have a field date with 2014-11-14 and i display 15/11/2014

Here is how i create the field in the form in my view:

field($model, 'date_ini')->widget(DateControl::classname(), [ ]); ?>

Any idea where my problem is?
Thank's

Language in DateControl Widget

Hi Kartik, your extensions are great!

but how con i set italian language in Widget?

<?php echo $form->field($model, 'created_at')->widget(DateControl::classname(), [
                                        'type'=>DateControl::FORMAT_DATETIME,
                                        'pluginOptions' => ['language' => 'it'],
                                        ]); ?> 

This is my module config:

'modules' => [
    'datecontrol' => [
        'class' => 'kartik\datecontrol\Module',

        // format settings for displaying each date attribute
        'displaySettings' => [
            Module::FORMAT_DATE => 'd/m/Y',
            Module::FORMAT_TIME => 'H:i:s',
            Module::FORMAT_DATETIME => 'd/m/Y H:i:s',
        ],

        // format settings for saving each date attribute
        'saveSettings' => [
            Module::FORMAT_DATE => 'Y-m-d', // saves as unix timestamp
            Module::FORMAT_TIME => 'H:i:s',
            //Module::FORMAT_DATETIME => 'Y-m-d H:i:s',
            Module::FORMAT_DATETIME => 'U',
        ],

        // automatically use kartik\widgets for each of the above formats
        'autoWidget' => true,

    // other settings
    ]
],

Duble ajax request for conversion.

echo $form->field($model, 'date')->widget(DateControl::className(), [
    'type' => DateControl::FORMAT_DATE,
    'options' => [
        'type' => DatePicker::TYPE_COMPONENT_APPEND,
    ],
]);

I click to day and running two ajax request for conversion.

2015-01-24 23 56 59

Wrong month display (default value in input field)

Config:

'modules' => [
    'datecontrol' => [
        'class' => 'kartik\datecontrol\Module',
        'displaySettings' => [
            'date' => 'd.m.Y',
        ],
    ],
],

View:

<?= $form->field($model, 'date')->widget(
    DateControl::classname(),
    [
        'type' => DateControl::FORMAT_DATE
    ]
) ?>

Model:

$this->date = '2014-06-23';

Wrong display (value):
image

HTML:

<script type="text/javascript">var datecontrol_07e440d9 = {"idDisp":"attendancetime-date-disp","idSave":"attendancetime-date","url":"\/datecontrol\/parse\/convert","type":"date","saveFormat":"Y-m-d","dispFormat":"d.m.Y"};

var datepicker_b5183978 = {"format":"dd.mm.yyyy"};

var timepicker_37b1b0bd = {"showMeridian":false};
</script>
...
<input type="text" id="attendancetime-date-disp" class="form-control" name="date-attendancetime-date" value="23.0.2014" data-plugin-name="datepicker" data-plugin-options="datepicker_b5183978">

Select ok:
image


By using 'date' => 'd.M.Y' I get the display "23.6.2014" and when I select a date "07.Jun.2014".

Thanks!

Set the date value?

Hey buddy. Continuing to enjoy using these great widgets.

Should this work? It worked at one time... My date input box is empty however with this code.

        use kartik\datecontrol\DateControl;
        // Use a DateTimePicker input with ActiveForm and model validation enabled.
        $model->start_date = '2014-08-20';
        echo $form->field($model, 'start_date')
            ->widget(DateControl::classname(), [
            'type'=>DateControl::FORMAT_DATE
        ]);

Calculating the date on the web page

Hello,
I think it would be nice to pass timezone offset to a page view, and then calculate the date. Instead of calculating the date of Ajax requests.

Invalid Configuration

Hi everyone, I'm using datecontrol Module, I configured it in console.php just like is defined in https://github.com/kartik-v/yii2-datecontrol#module
In the form I have this:
$form->field($model, 'Fecha_fin')->widget(DateControl::classname(), [
'type'=>DateControl::FORMAT_DATE,
'ajaxConversion'=>false,
'options' => [
'pluginOptions' => [
'autoclose' => true
]
]
]);

but when I run it I have the next error: "The 'datecontrol' module MUST be setup in your Yii configuration file and must be an instance of 'kartik\datecontrol\Module'."
In what 'm failing?thanks!

Bad Request

I'm getting Bad Request (#400) when changing dates in views.

Thanks!

Since update only broken date

Hi, since the last update I ended up with a broken date format that looks like :
10.ii.o
What do I need to Change to follow the new formatter code?

Wrong capitalization in 'autoClose'

Hi.
In this url https://github.com/kartik-v/yii2-datecontrol I can see that in this line
Module::FORMAT_DATE => ['type'=>2, 'pluginOptions'=>['autoclose'=>true]], // example
autoclose is written with a lower case 'c'.

But in this url http://demos.krajee.com/datecontrol it still shows with an upper case 'C'.
Module::FORMAT_DATE => ['type'=>2, 'pluginOptions'=>['autoClose'=>true]], // example

Thus auto close of the date picker dialog doesn't work until I changed it to a lower case 'c' since I copied it from the example on the demo page.

DateControl Ajax call failed

Sorry I come again. I have next issue I can't solve it.

I call DateControl with DatetimePicker and DatePicker on my page three time. First steps are working but after change of date there was no update. I made hidden save field visible an I saw that there is not update. see:
date_not_updated

Then I saw in Yii Debugger a HttpExcepton: 400, see
error in yii debug

Next step was debugging the routing process. I found out that crsf token validation in Yii fails. see
datecontrol_missing_crsf_token

I ask me why does your demo page works and I have no chance to get it running.

I looked up in the internet a little bit. One article tells that _crsf:yii.getCrsfToken() must be added. In another Github discussion Quinagxue tells that Yii should submit crsf token automatically. see links:
(http://stackoverflow.com/questions/23679332/ajax-request-from-a-js-file-to-yii2-controller-function)
(yiisoft/yii2#1367)
Probably Quiangxue means AJAX calls in which all data of the form is submitted (incl. _crsf) or Yii2 has changed something.

Question:
Why don't you copy the format method in DatePicker.js and change it to PHP format pattern (Y-m-d instead of yyyy-mm-dd)? An AJAX call could be optional for complex validation and reformatting.

I want to thank you very much for your good and quick work.
Enrica

Missing file bootstrap-datepicker.fr-FR.js

Yii2 transalation programe is :
"The format for the language/locale is ll-CC where ll is a two- or three-letter lowercase code for a language according to ISO-639 and CC is the country code according to ISO-3166."
as seen in "https://github.com/yiisoft/yii2/blob/master/docs/guide/tutorial-i18n.md"

in my main.local.php i set :
'language' => 'fr-FR',

i got an error, missing a file :
kartik-v\yii2-widget-datepicker\assets\js\locales\bootstrap-datepicker.fr-FR.js
i juste renamed "bootstrap-datepicker.fr.js" to "bootstrap-datepicker.fr-FR.js" to fix the issue and clean asset cache.

additionnaly "kartik-v\yii2-grid\messages" miss a "fr" translation, i don't find where to laucneh "yii message"

How to display simply date converted with datecontrol parameters?

Hi Kartik, sorry for this new question but i dont' find how to do this.

I'm using well yii2-datecontrol widget to get date input from the user in his timezone [displayFormat] and then save the date converted in my database [saveFormat]

Now i have to do the inverse. Get the date from the db [saveFormat] and convert to the user timezone [displayFormat] , and simply display it. For example

echo $model->date //display the date in saved timezone [saveFormat]

echo ??? //display the date in user timezone [displayFormat]

How can i do?
Thank's 1.000

Add input event

The problem is that when you press the submit event does not fire if the field does not lose focus and eventually the date does not change.
Why not add "input" event?

       $el.on('change', function () {
            if (isEmpty($el.val())) {
                $idSave.val('');
            } else {

        $el.on('change input', function () {
            if (isEmpty($el.val())) {
                $idSave.val('');
            } else {

Configuring yii2-dateControl with yii2-widget-datepicker.

Hi Kartikv sorry to bother you again, I have the following questions, I set DateControl with yii2-widget-datepicker, as he was passing parameters to display and save data.

My Config:

'modules' => [
    // Configuracion de Horas y Fechas.
    'datecontrol' =>  [
        'class' => 'kartik\datecontrol\Module',

        // format settings for displaying each date attribute (ICU format example)
        'displaySettings' => [
            kartik\datecontrol\Module::FORMAT_DATE => 'dd-MM-yyyy',
            kartik\datecontrol\Module::FORMAT_TIME => 'HH:mm',
            kartik\datecontrol\Module::FORMAT_DATETIME => 'dd-MM-yyyy HH:mm:ss a',
        ],

        // format settings for saving each date attribute (PHP format example)
        'saveSettings' => [
            kartik\datecontrol\Module::FORMAT_DATE => 'php:U', // saves as unix timestamp
            kartik\datecontrol\Module::FORMAT_TIME => 'php:H:i',
            kartik\datecontrol\Module::FORMAT_DATETIME => 'php:Y-m-d H:i:s',
        ],

        // set your display timezone
        'displayTimezone' => 'America/Caracas',

        // set your timezone for date saved to db
        'saveTimezone' => 'America/Caracas',

        // automatically use kartik\widgets for each of the above formats
        'autoWidget' => true,

        // default settings for each widget from kartik\widgets used when autoWidget is true
        'autoWidgetSettings' => [
            kartik\datecontrol\Module::FORMAT_DATE => ['type'=>1, 'pluginOptions'=>['autoclose'=>true]], // example
        ],
    ],

Example FileRange with Datepicker:

echo kartik\field\FieldRange::widget([
    'form' => $form,
    'model' => $model,
    'label' => 'Seleccione Duración del Horario',
    'attribute1' => 'Turn003',
    'attribute2' => 'Turn004',
    'useAddons' => false,
    'type' => kartik\field\FieldRange::INPUT_DATE,
]);

As you can pass yii2-widgets-datepicker the display format parameters and save format, is this possible,

Thks,

Time value in datetime fiels is not writed in db

It is strange:

my config (myapp/common/config/main.app):

'ru-RU', 'vendorPath' => dirname(dirname(**DIR**)) . '/vendor', 'components' => [ 'i18n' => [ 'translations' => [ 'frontend_' => [ 'class' => 'yii\i18n\PhpMessageSource', 'basePath' => '@common/messages', ], 'backend_' => [ 'class' => 'yii\i18n\PhpMessageSource', 'basePath' => '@common/messages', ], ], ], 'cache' => [ 'class' => 'yii\caching\FileCache', ], 'user' => [ 'class' => 'amnah\yii2\user\components\User', ], ], ``` 'modules' => [ 'user' => [ 'class' => 'amnah\yii2\user\Module', ], 'gridview' => [ 'class' => 'kartik\grid\Module', ], 'datecontrol' => [ 'class' => 'kartik\datecontrol\Module', 'displaySettings' => [Module::FORMAT_DATE => 'd.m.Y', Module::FORMAT_TIME => 'H:i:s', Module::FORMAT_DATETIME => 'dd.MM.yyyy HH:mm'], 'displayTimezone' => 'Asia/Almaty', 'saveSettings' => [Module::FORMAT_DATE => 'php:U', // saves as unix timestamp Module::FORMAT_TIME => 'php:H:i:s', Module::FORMAT_DATETIME => 'php:Y-m-d H:i:s'], 'saveTimezone' => 'Asia/Almaty', ], ], ``` ]; my _form.php
.... field($model, 'lasttalk') ?> field($model, 'lasttalk')->widget(DateControl::classname(),. ['type' => DateControl::FORMAT_DATETIME]) ?> ...

In this configuration, date part saved correct, but time part saved as "00:00:00" everytime.

What wrong?

The format of <field> is invalid

I've tried to set up the Date Control exactly as described in your documentation, and no matter what I do, I get the error message, "The format of Purchase Date is invalid." I'm hoping you can point to what I'm doing wrong.

In my backend/config/main.php, in the 'modules' section, I've got this:

'datecontrol' => [
                'class' => 'kartik\datecontrol\Module',

                // format settings for displaying each date attribute (ICU format example)
                'displaySettings' => [
                    Module::FORMAT_DATE => 'dd-MM-yyyy',
                    Module::FORMAT_TIME => 'HH:mm:ss ',
                    Module::FORMAT_DATETIME => 'dd-MM-yyyy HH:mm:ss a',
                ],
                // format settings for saving each date attribute (PHP format example)
                'saveSettings' => [
                    Module::FORMAT_DATE => 'php:U', // saves as unix timestamp
                    Module::FORMAT_TIME => 'php:H:i:s',
                    Module::FORMAT_DATETIME => 'php:Y-m-d H:i:s',
                ],

                // set your display timezone
                // 'displayTimezone' => 'Asia/Kolkata',

                // set your timezone for date saved to db
                'saveTimezone' => 'UTC',
                // automatically use kartik\widgets for each of the above formats
                'autoWidget' => true,

            ],

And in _form.php, my field is configured like this:

<?=
                        $form->field($model, 'purchase_date')->widget(DateControl::classname(), [
                            'type'           => DateControl::FORMAT_DATE,
                            // 'ajaxConversion' => true,
                            'options'        => [
                                'pluginOptions' => [
                                    'autoclose' => true
                                ]
                            ]
                        ]
                        );
                    ?>

The DatePicker displays in the form, but when I select a date from it (not entering the date manually) and attempt to save, I get this:
datepicker error
Can you help identify what I'm doing wrong?

Adjusting AutoWidget Plugin Options

It seems I can't add any extra plugin options if autoWidget is true.
I'd like to simply change the minuteStep value, but this won't work ..

echo $form->field($model, 'start_at')->widget(DateControl::classname(), [
    'type'=>DateControl::FORMAT_DATETIME,
    'options' => [
        'type' => \kartik\widgets\DateTimePicker::TYPE_COMPONENT_APPEND,
        'options' => ['placeholder' => 'Select start date/time ...'],
        'pluginOptions' => ['minuteStep' => 1],
    ],
]);

If I remove the 'pluginOptions', it works fine but minuteStep value is obviously not changed :-(
Am I doing something wrong or is it a bug/intended?

Thanks for this very useful extension by the way.

DateTime createFromFormat wrongly uses current timestamp in time part for bare DATE format

The DateTime::createFromFormat method has an issue where a DateTime object created without explicitly providing the time portion will have the current time set instead of the default 00:00:00. This will lead to unfavorable comparison of dates and timezones. A fix will be provided whereby, when using FORMAT_DATE - the time portion will be internally auto set to 00:00:00 to ensure right date conversion and timezone comparison.

Changes in formatter

Hello Kartik
Cebe has refactored formatter in Yii2 completely. In difference to my original version he hasn't kept the compatibility. Formatter is in path yii\i18n only. The command ->formatter->dateFormat brings a short term like medium or ICU like dd/mm/yyyy format or a php format prefixed with php:. With this changes your module datecontrol isn't working anymore if the format isn't set hardcoded in one of the config levels.

For conversion he built a new helper class yii\helpers\FormatConverters based on yii\helpers\BaseFormatConverters. This class converts from ICU to PHP or PHP to ICU or ICU to JUI or PHP to JUI including the terms short, medium, long or full.

You should adapt your function Module->getDisplayFormat. As an example you can see how cebe has modified JUI Datepicker see diff view. I would modify your bootstrap datepicker in the initial process. If pluginOptions['format']isn't preset it takes format from Yii application (Formatter and FormatConversion). With this changes an application can change formats dynamically per language definition.

Thank you.

Automatic save Date and Time fields when insert new record on table

Hi, i'm looking yii2-datecontrol a i think it's a very good extension.
I see how to set up a widget, but i have the necessity to set up Date and Time fields with the right format automatically each time i create a new record on my table.

I think to use a Behavior or a BeforeSave class but i don't know if and how can i use yii-datecontrol also into the model.

Thank's

DateTimePicker "right"-Button with unexpected behaviour

Hello! When using the DateTimePicker it is not possible to switch to another month by clicking the "right"-Button. This should be the expected behaviour. See attached screenshots. You can also test this in your demo.

btw: Thanks for the great widgets!! Very nice work!

01

02

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.