Krajee

DateRangePicker

Thankful to Krajee! BUY A COFFEEor to get more out of us.
An advanced date range picker input for Yii Framework 2 based on bootstrap-daterangepicker plugin. The date range picker widget is styled for Bootstrap 5.x / 4.x / 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.

Tip

Not seeing the updated content on this page! Hard refresh your browser to clean cache for this page (e.g. SHIFT-F5 on Windows Chrome)

DateRange supports configuration of the bootstrap library version so that you can use this either with any Bootstrap version 3.x and above. For setting up the bootstrap version for your extension, you can configure the DateRange::bsVersion property to one of the following.

  • To use with bootstrap 3 library - you can set DateRange::bsVersion property to any string starting with 3 (e.g. 3 or 3.3.7 or 3.x)

  • To use with bootstrap 4 library - you can set DateRange::bsVersion property to any string starting with 4 (e.g. 4 or 4.6.0 or 4.x)

  • To use with bootstrap 5 library - you can set DateRange::bsVersion property to any string starting with 5 (e.g. 5 or 5.1.0 or 5.x)

The following sections describe the pre-requisites for enabling Bootstrap library specific version support in your application and other related controls/overrides.

Global Bootstrap Version


Generally, you may also want to set a default version globally for all Krajee Extensions (instead of setting it for each widget or extension separately). In order to do this, you can setup the bsVersion property within Yii 2 application params (i.e. Yii::$app->params['bsVersion']). To set this up, add this section of code to your application params configuration file (e.g. config/params.php):

'params' => [
    'bsVersion' => '5.x', // this will set globally `bsVersion` to Bootstrap 5.x for all Krajee Extensions
    // other settings
    // 'adminEmail' => 'admin@example.com'
]

If DateRange::bsVersion property is set, in addition to Yii::$app->params['bsVersion'], the extension level setting (DateRange::bsVersion property) will override the Yii::$app->params['bsVersion']. If DateRange::bsVersion property is not set, and Yii::$app->params['bsVersion'] is also not set, DateRange::bsVersion property will default to 3.x (i.e. Bootstrap 3.x version will be assumed as default).

Yii2 Bootstrap Dependency


You need to install one of yiisoft/yii2-bootstrap or yiisoft/yii2-bootstrap4 or yiisoft/yii2-bootstrap5 extensions manually in your application to enable Bootstrap 3.x or 4.x or 5.x functionality respectively. This dependency has not been pre-built into the composer configuration for Krajee extensions, to allow better control to the developers in configuring their bootstrap library version. If bsVersion is set to 5.x and yiisoft/yii2-bootstrap5 is not installed, then an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap5 extension. If bsVersion is set to 4.x and yiisoft/yii2-bootstrap4 is not installed, then an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap4 extension. Similarly, if bsVersion is set to 3.x and yiisoft/yii2-bootstrap is not installed, an exception message will be thrown mentioning you to install the yiisoft/yii2-bootstrap extension.

To install yiisoft/yii2-bootstrap5, add the repo to the require section of your application's composer.json.

"yiisoft/yii2-bootstrap5": "@dev"

To install yiisoft/yii2-bootstrap4, add the repo to the require section of your application's composer.json.

"yiisoft/yii2-bootstrap4": "@dev"

To install yiisoft/yii2-bootstrap, add the repo to the require section of your application's composer.json.

"yiisoft/yii2-bootstrap": "@dev"

Override Bootstrap CSS/JS


The Krajee extension asset bundle(s) by default depend on one of the following asset bundles to load the Bootstrap CSS and JS:

  • yii\bootstrap\BootstrapAsset and/or yii\bootstrap\BootstrapPluginAsset for bootstrap 3.x (bsVersion = 3 setting)

  • yii\bootstrap4\BootstrapAsset and/or yii\bootstrap4\BootstrapPluginAsset for bootstrap 4.x ( bsVersion = 4 setting)

  • yii\bootstrap5\BootstrapAsset and/or yii\bootstrap5\BootstrapPluginAsset for bootstrap 5.x (bsVersion = 5 setting)

This is controlled by the property bsDependencyEnabled within the asset bundle (which defaults to true). One can override this and prevent the default yii2 bootstrap assets (CSS & JS) from loading by doing one or all of the following:

  • Global Override: Set Yii::$app->params['bsDependencyEnabled'] to false in your Yii 2 application config params.php. This setting will be applied for all Krajee Extension Asset Bundles that depend on Bootstrap assets.

    'params' => [
        'bsDependencyEnabled' => false, // this will not load Bootstrap CSS and JS for all Krajee extensions
        // you need to ensure you load the Bootstrap CSS/JS manually in your view layout before Krajee CSS/JS assets
        //
        // other params settings below
        // 'bsVersion' => '5.x',
        // 'adminEmail' => 'admin@example.com'
    ]
    
  • Asset Bundle Specific Override: Set bsDependencyEnabled to false for the specific asset bundle within Yii2 Asset Manager component in your Yii 2 application config file.

    // ...
    'components' => [
        'assetManager' => [
            'bundles' => [
                'kartik\form\ActiveFormAsset' => [
                    'bsDependencyEnabled' => false // do not load bootstrap assets for a specific asset bundle
                ],
            ],
        ],
    ],
    

Note

When setting bsDependencyEnabled to false, you need to ensure that your app code/view layout loads the Bootstrap CSS and JS on your view before the Krajee CSS/JS are loaded to ensure that the Krajee extension JS plugins and CSS styles do not get broken.

Icons for Bootstrap


Bootstrap 5.x / 4.x does not include glyphicons or any other icons framework bundled with the library. Krajee extensions therefore will use Font Awesome 5.x icons instead of glyphicons when working with Bootstrap 5.x / 4.x. You can download Font Awesome 5.x icons from the icons website. Alternatively, you can load the free version of Font Awesome from their CDN.

For Krajee extensions and demos, the Font Awesome Free version is used and loaded as the Icons Display Package on all the Yii2 demo layouts. To include font awesome assets on your page, include the following markup on the HEAD section of your view layout file, when bsVersion is set to 4.x or 5.x.

  • Option 1: Font CSS version of Font Awesome:

    <!-- on your view layout file HEAD section -->
    <link rel="stylesheet" href="https://use.fontawesome.com/releases/v5.3.1/css/all.css">
    
  • Option 2: SVG / JS version of Font Awesome (recommended for cleaner scaling vector icons and features like icon layers):

    <!-- on your view layout file HEAD section -->
    <script defer src="https://use.fontawesome.com/releases/v5.3.1/js/all.js" crossorigin="anonymous"></script>
    

    Alternatively, you can use the FontAwesomeAsset from the kartik-v/yii2-icons package to load the SVG/JS version.

    // on your view layout file
    use kartik\icons\FontAwesomeAsset;
    FontAwesomeAsset::register($this);
    

The yii2-date-range extension can be installed automatically or manually using one of these options:

Composer Package Manager Recommended


Installation via Composer is the recommended and most easy option to install Krajee Yii2 extensions. You can install yii2-date-range via composer package manager. Either run:

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

or add:

"kartik-v/yii2-date-range": "dev-master"

to your application's composer.json file.

Manual Install


You may also manually install the extension to your project (in case your composer install does not work). Just download the source ZIP or TAR ball and extract the extension asset files and folders into your project. You may need to install dependencies manually and also set the namespaces to the extensions in your Yii2 extensions configurations manually.

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:
  • bsVersion: string | int, the bootstrap library version to be used for the extension. Refer the Bootstrap Info section for details and pre-requisites on setting this property.

    • To use with Bootstrap library - you can set this to any string starting with 3 (e.g. 3 or 3.3.7 or 4.x / 3.x)

    • To use with bootstrap 4 - you can set this to any string starting with 4 (e.g. 4 or 4.6.0 or 4.x)

    • To use with bootstrap 5 - you can set this to any string starting with 4 (e.g. 5 or 5.1.0 or 5.x)

  • bsColCssPrefixes: array, the bootstrap grid column css prefixes mapping, the key is the bootstrap versions, and the value is an array containing the sizes and their corresponding grid column css prefixes. The class using this trait, must implement kartik\base\BootstrapInterface. If not set will default to:.

    [
       3 => [
          self::SIZE_X_SMALL => 'col-xs-',
          self::SIZE_SMALL => 'col-sm-',
          self::SIZE_MEDIUM => 'col-md-',
          self::SIZE_LARGE => 'col-lg-',
          self::SIZE_X_LARGE => 'col-lg-',
          self::SIZE_XX_LARGE => 'col-lg-',
       ],
       4 => [
          self::SIZE_X_SMALL => 'col-',
          self::SIZE_SMALL => 'col-sm-',
          self::SIZE_MEDIUM => 'col-md-',
          self::SIZE_LARGE => 'col-lg-',
          self::SIZE_X_LARGE => 'col-xl-',
          self::SIZE_XX_LARGE => 'col-xl-',
       ],
       5 => [
          self::SIZE_X_SMALL => 'col-',
          self::SIZE_SMALL => 'col-sm-',
          self::SIZE_MEDIUM => 'col-md-',
          self::SIZE_LARGE => 'col-lg-',
          self::SIZE_X_LARGE => 'col-xl-',
          self::SIZE_XX_LARGE => 'col-xxl-',
       ],
    ];
    
  • 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 library 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')"],
        (DATA FROM presetFilterDays based on includeDaysFilter setting),
        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')"],
        (DATA FROM presetFilterMonths based on includeMonthsFilter setting),
    ];
    
  • includeDaysFilter: boolean whether to add additional preset filter options for days (applicable only when presetDropdown is true). Applicable only when presetDropdown is true. Defaults to true. If this is set to true, the following additional preset filter option(s) will be available:

    • Last {n} Days

    where n will be picked up from the list of filter days set via presetFilterDays

  • includeMonthsFilter: boolean whether to add additional preset filter options for months (applicable only when presetDropdown is true). Applicable only when presetDropdown is true. Defaults to true. If this is set to true, the following additional preset filter option(s) will be available:

    • Last {n} Months

    where n will be picked up from the list of filter months set via presetFilterMonths

  • presetFilterDays: array list of preset filter days (which will be shown as last {n} days). Applicable only when presetDropdown is true. Defaults to [7, 30].

  • presetFilterMonths: array list of preset filter months (which will be shown as last {n} months). Applicable only when presetDropdown is true. Defaults to [3, 6, 12].

  • 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="fas fa-calendar-alt"></i>
    </span>
    <span class="form-control text-right text-end">
        <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.

A disabled Date Range Picker

A readonly Date Range Picker

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orm\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="fas fa-calendar-alt"></i>']],
    'options'=>['class'=>'drp-container mb-2']
])->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
<div class="input-group-append">
    <span class="input-group-text">
        <i class="fas fa-calendar-alt"></i>
    </span>
</div>
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.
// Note that placeholder setting in this case will be displayed when value is null
// Also the includeMonthsFilter setting will display LAST 3, 6 and 12 MONTHS filters.
echo '<label class="control-label">Date Range</label>';
echo '<div class="drp-container">';
echo DateRangePicker::widget([
    'name'=>'date_range_2',
    'presetDropdown'=>true,
    'convertFormat'=>true,
    'includeMonthsFilter'=>true,
    'pluginOptions' => ['locale' => ['format' => 'd-M-y']],
    'options' => ['placeholder' => 'Select range...']
]);
echo '</div>';

//  A disabled Date Range Picker
echo '<label class="control-label">Date Range (Disabled)</label>';
echo '<div class="drp-container">';
echo DateRangePicker::widget([
    'name'=>'date_range_2a',
    'value'=>'2015-10-19 - 2015-11-03',
    'convertFormat'=>true,
    'disabled' => true,
    'pluginOptions'=>[
        'locale'=>['format'=>'Y-m-d']
    ]
]);
echo '</div>';

//  A readonly Date Range Picker
echo '<label class="control-label">Date Range (Readonly)</label>';
echo '<div class="drp-container">';
echo DateRangePicker::widget([
    'name'=>'date_range_2a',
    'value'=>'2015-10-19 - 2015-11-03',
    'convertFormat'=>true,
    'readonly' => true,
    'pluginOptions'=>[
        'locale'=>['format'=>'Y-m-d']
    ]
]);
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.

Note

You can now visit the Krajee Webtips Q & A forum for searching OR asking questions OR helping programmers with answers on these extensions and plugins. For asking a question click here. Select the appropriate question category (i.e. Krajee Plugins) and choose this current page plugin in the question related to field.

The comments and discussion section below are intended for generic discussions or feedback for this plugin. Developers may not be able to search or lookup here specific questions or tips on usage for this plugin.

 
visitors to Krajee Yii2 Demos since 22-May-2017