DateRangePicker

Latest Stable Version Latest Unstable Version Total Downloads Monthly Downloads Daily Downloads
Thankful to Krajee!
to get more out of us.

NOTE: This extension depends on the kartik-v/yii2-krajee-base extension which in turn depends on the yiisoft/yii2-bootstrap extension. Check the composer.json for this extension's requirements and dependencies that may be updated by composer.

An advanced date range picker input for Yii Framework 2 based on bootstrap-daterangepicker plugin. The date range picker widget is styled for Bootstrap 3.x and creates a dropdown menu from which a user can select a range of dates. If the plugin is invoked with no options, it will present two calendars to choose a start and end date from. Optionally, you can provide a list of date ranges the user can select from of choosing dates from the calendars. If attached to a text input, the selected dates will be inserted into the text box. Otherwise, you can provide a custom callback function to receive the selection.

Additional enhancements added for this widget (by Krajee):

  • allows ability to work with Bootstrap input group addons and set the picker position to point at the input-group-addon icon.
  • enhanced translation features providing ability to add/configure your translation for each language. In order to create your own translation, please follow these steps.
  • automatically convert format from PHP Date/time format to Moment.js Date/time format.
  • automatically trigger change of base field to enforce Yii ActiveField validation
  • ability to set the widget to display a preset dropdown of date options within a container (and hidden input).
  • style the container options as per your need using templates
  • automatically disable date-range based on disabled/readonly options.
View a complete demo.

The preferred way to install this extension is through composer. Either run:

$ php composer.phar require kartik-v/yii2-date-range "*"

or add:

"kartik-v/yii2-date-range": "*"

to the require section of your composer.json file. Then run:

php composer.phar update

to get the updated package on your application install.

The DateRangePicker widget supports all the parameters similar to the \yii\widgets\InputWidget widget. In addition, the widget allows you to configure the following properties:
  • callback: string, the javascript callback to be passed to the plugin constructor. Note: a default value is set for this property when you set hideInput to false, OR you set useWithAddon to true or autoUpdateOnInit to false. If you set a value here it will override any auto-generated callbacks. Refer the plugin usage documentation for more details on this.

  • autoUpdateOnInit: boolean, whether to auto update the input on initialization. If set to false, this will auto set the plugin's autoUpdateInput property to false. A default callback will be auto-generated when this is set to false. Setting this to false is recommended for cases where you do not want the input change to be triggered on initialization like in gridview filters.

  • hideInput: boolean, whether to hide the input (e.g. instead of an editable input, you just want to show a dropdown). If set to true, the input will be hidden. The plugin will be initialized on a container element (default 'div'), using the container template. A default callback will be automatically generated in this case to display the selected range value within the container. Defaults to false.

  • useWithAddon: boolean, whether you are using the picker with a Bootstrap 3 input group addon. You can set it to true, when hideInput is false, and you wish to show the picker position more correctly at the input-group-addon icon. A default callback will be automatically setup in this case to generate the selected range value for the input. Defaults to false.

  • initRangeExpr: boolean, whether, the widget should initialize all the list values set in pluginOptions['ranges'] and auto-convert all values to yii\web\JsExpression. Defaults to true.

  • presetDropdown: boolean, whether, a preset dropdown should be automatically generated. If set to true, this will automatically generate a preset list of ranges (pluginOptions['ranges']) for selection. Setting this to true, will also automatically set initRangeExpr to true. Refer the plugin events documentation for more details on setting ranges. The following values are automatically set when this is set to true. Defaults to false.

    initRangeExpr = true;
    pluginOptions['ranges'] = [
        Yii::t('kvdrp', "Today") => ["moment().startOf('day')", "moment()"],
        Yii::t('kvdrp', "Yesterday") => ["moment().startOf('day').subtract(1,'days')", "moment().endOf('day').subtract(1,'days')"],
        Yii::t('kvdrp', "Last {n} Days", ['n' => 7]) => ["moment().startOf('day').subtract(6, 'days')", "moment()"],
        Yii::t('kvdrp', "Last {n} Days", ['n' => 30]) => ["moment().startOf('day').subtract(29, 'days')", "moment()"],
        Yii::t('kvdrp', "This Month") => ["moment().startOf('month')", "moment().endOf('month')"],
        Yii::t('kvdrp', "Last Month") => ["moment().subtract(1, 'month').startOf('month')", "moment().subtract(1, 'month').endOf('month')"],
    ];
    
  • convertFormat: boolean whether the widget should automatically format the date from the PHP DateTime format to the Moment Datetime format.. Defaults to false.

  • containerTemplate: string the template for rendering the container, when hideInput is set to true. The special tag {input} will be replaced with the hidden form input. In addition, the element with css class range-value will be replaced by the calculated plugin value. The special tag {value} will be replaced with the value of the hidden form input during widget initialization (when hideInput is set to true).

    <span class="input-group-addon">
        <i class="glyphicon glyphicon-calendar"></i>
    </span>
    <span class="form-control text-right">
        <span class="pull-left">
            <span class="range-value">{value}</span>
        </span>
        <b class="caret"></b>
        {input}
    </span>
    
  • containerOptions: array, the HTML attributes for container, if hideInput is set to true. The following special options are recognized:

    • tag: string, the HTML tag for rendering the container. Defaults to div.

  • options: array the HTML attributes for the input

  • i18n: array, the internalization configuration for this module. Defaults to:

    [
        'class' => 'yii\i18n\PhpMessageSource',
        'basePath' => '@kvdrp/messages',
        'forceTranslation' => true
    ]
    
  • startAttribute: string, the attribute name which you can set optionally to track changes to the range start value. One of the following actions will be taken when this is set:

    • If using with model, an active hidden input will be automatically generated using this as an attribute name for the start value of the range.

    • If using without model, a normal hidden input will be automatically generated using this as an input name for the start value of the range.

  • endAttribute: string, the attribute name which you can set optionally to track changes to the range end value. One of the following actions will be taken when this is set:

    • If using with model, an active hidden input will be automatically generated using this as an attribute name for the end value of the range.

    • If using without model, a normal hidden input will be automatically generated using this as an input name for the end value of the range.

  • startInputOptions: array, the HTML attributes for the start input (applicable only if startAttribute is set). If using without a model, you can set a start value here within the value property.

  • endInputOptions: array, the HTML attributes for the end input (applicable only if endAttribute is set). If using without a model, you can set a end value here within the value property.

  • pluginOptions: array the JQuery plugin options for the bootstrap-date-range plugin. You can control many options for the plugin. Refer the plugin options documentation for details of all options that can be setup. The following important parameters determine how your output is generated:

    • locale: array, the plugin locale settings. The following properties are important:

      • format: string, the format for date time formatting. If convertFormat is set to true, this will be assumed as a PHP date time format and converted to Moment datetime format for javascript.

      • separator: string, the separator string to display between the start and end date when populating a text input the picker is attached to. Defaults to ' - '.

  • pluginEvents: array the bootstrap-date-range plugin events. You must define events in event-name => event-function format. Refer the plugin events documentation for details. All events will be stacked in the sequence passed. For example:

    pluginEvents = [
    "show.daterangepicker" => "function() { log("show.daterangepicker"); }",
    "hide.daterangepicker" => "function() { log("hide.daterangepicker"); }",
    "apply.daterangepicker" => "function() { log("apply.daterangepicker"); }",
    "cancel.daterangepicker" => "function() { log("cancel.daterangepicker"); }",
    ];
    
View a complete demo.

Check the messages folder in the extension repository. You can check the message file for your locale sub-folder and update the yii i18n message file kvdrp.php as a new pull request. If the locale sub folder does not exist, you can create a new one editing/using the config.php file. Message files can be generated for your locale using yii message console command.

View a complete demo.

DateRangePicker with ActiveForm and model. Check the required model validation for the attribute. This also features configuration of Bootstrap input group addon. Note that in this example, the model attribute has an initial value.

DateRangePicker without ActiveForm and with an initial default value, a custom date format, and a custom separator. Auto conversion of date format from PHP DateTime to Moment.js DateTime is set to true. Custom addon markup on the right and make the picker open in the direction right to left.

 
DateRangePicker in a dropdown format (uneditable/hidden input) and uses the preset dropdown.

Date and Time picker with time increment of 15 minutes and without any input group addons.

Single date picker without range.

Single date and time picker without range.

Advanced configuration using separate start and end attributes to store information. Note that you can have these attributes have their own validation rules in the model. In the scenario that your base attribute (e.g. kvdate1 in this example), does not have an initial value, then the initial value will be auto derived from the start and end attributes.

Extension of above scenario using separate start and end attributes but without a model. You can set the initial value within startInputOptions and endInputOptions.

Variation of above scenario by setting a value directly in base attribute instead of setting separate attributes. In this case the individual attributes will be set automatically.
use kartik\daterange\DateRangePicker;
use kartik\widgets\ActiveForm;
$form = ActiveForm::begin();
// DateRangePicker with ActiveForm and model. Check the `required` model validation for 
// the attribute. This also features configuration of Bootstrap input group addon.
echo $form->field($model, 'date_range', [
    'addon'=>['prepend'=>['content'=>'<i class="glyphicon glyphicon-calendar"></i>']],
    'options'=>['class'=>'drp-container form-group']
])->widget(DateRangePicker::classname(), [
    'useWithAddon'=>true
]);

// DateRangePicker without ActiveForm and with an initial default value, a custom date, 
// format and a custom separator. Auto conversion of date format from PHP DateTime to 
// Moment.js DateTime is set to <code>true</code>. Custom addon markup on the right and
// make the picker open in the direction right to left.
$addon = <<< HTML
<span class="input-group-addon">
    <i class="glyphicon glyphicon-calendar"></i>
</span>
HTML;
echo '<label class="control-label">Date Range</label>';
echo '<div class="input-group drp-container">';
echo DateRangePicker::widget([
    'name'=>'date_range_1',
    'value'=>'01-Jan-14 to 20-Feb-14',
    'convertFormat'=>true,
    'useWithAddon'=>true,
    'pluginOptions'=>[
        'locale'=>[
            'format'=>'d-M-y',
            'separator'=>' to ',
        ],
        'opens'=>'left'
    ]
]) . $addon;
echo '</div>';

// DateRangePicker in a dropdown format (uneditable/hidden input) and uses the preset dropdown.
echo '<label class="control-label">Date Range</label>';
echo '<div class="drp-container">';
echo DateRangePicker::widget([
    'name'=>'date_range_2',
    'presetDropdown'=>true,
    'hideInput'=>true
]);
echo '</div>';

//  Date and Time picker with time increment of 15 minutes and without any input group addons.
echo DateRangePicker::widget([
    'name'=>'date_range_3',
    'value'=>'2015-10-19 12:00 AM - 2015-11-03 01:00 PM',
    'convertFormat'=>true,
    'pluginOptions'=>[
        'timePicker'=>true,
        'timePickerIncrement'=>15,
        'locale'=>['format'=>'Y-m-d h:i A']
    ]            
]);

// Single date picker without range.
echo '<div class="input-group drp-container">';
echo DateRangePicker::widget([
    'name'=>'date_range_4',
    'value'=>'01/12/2015',
    'useWithAddon'=>true,
    'pluginOptions'=>[
        'singleDatePicker'=>true,
        'showDropdowns'=>true
    ]
]) . $addon;
echo '</div>';

// Single date time picker without range.
echo '<div class="input-group drp-container">';
echo DateRangePicker::widget([
    'name'=>'date_range_5',
    'value'=>'2015-10-19 12:00 AM',
    'useWithAddon'=>true,
    'convertFormat'=>true,
    'pluginOptions'=>[
        'timePicker'=>true,
        'timePickerIncrement'=>15,
        'locale'=>['format' => 'Y-m-d h:i A'],
        'singleDatePicker'=>true,
        'showDropdowns'=>true
    ]
]) . $addon;
echo '</div>';

// Advanced configuration using separate start and end attributes to store information.
// Note that you can have these attributes have their own validation rules in the model.
// In the scenario that your base attribute (e.g. `kvdate1` in this example), does not 
// have an initial value, then the initial value will be auto derived from the start and 
// end attributes.
$model->datetime_start = '2016-02-11';
$model->datetime_end = '2016-03-15';
echo '<div class="input-group drp-container">';
echo DateRangePicker::widget([
    'model'=>$model,
    'attribute' => 'kvdate1',
    'useWithAddon'=>true,
    'convertFormat'=>true,
    'startAttribute' => 'datetime_start',
    'endAttribute' => 'datetime_end',
    'pluginOptions'=>[
        'locale'=>['format' => 'Y-m-d'],
    ]
]) . $addon;
echo '</div>';

// Extension of above scenario using separate start and end attributes 
// but without a model. You can set the initial value within 
// `startInputOptions` and `endInputOptions`.
echo '<div class="input-group drp-container">';
echo DateRangePicker::widget([
    'name'=>'kvdate2',
    'useWithAddon'=>true,
    'convertFormat'=>true,
    'startAttribute' => 'from_date',
    'endAttribute' => 'to_date',
    'startInputOptions' => ['value' => '2017-06-11'],
    'endInputOptions' => ['value' => '2017-07-20'],
    'pluginOptions'=>[
        'locale'=>['format' => 'Y-m-d'],
    ]
]) . $addon;
echo '</div>';

// Variation of above scenario by setting a value directly in base attribute
// instead of setting separate attributes. In this case the individual
// attributes will be set automatically. 
echo '<div class="input-group drp-container">';
echo DateRangePicker::widget([
    'name'=>'kvdate3',
    'value' => '2018-10-04 - 2018-11-14',
    'useWithAddon'=>true,
    'convertFormat'=>true,
    'startAttribute' => 'from_date',
    'endAttribute' => 'to_date',
    'pluginOptions'=>[
        'locale'=>['format' => 'Y-m-d'],
    ]
]) . $addon;
echo '</div>';
ActiveForm::end();

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