yII2:Date filter how to in Gridview

11,558

You can use kartik Date Range Picker for that :

1.check this out : https://github.com/kartik-v/yii2-date-range

Implementation

1.In your view : use kartik\daterange\DateRangePicker;

2.If you are using grid view

  • Add this code in attribute

    [
     'attribute'=>'Date',
     'label'=>'Date',
     'format'=>'text',
     'filter'=> '<div class="drp-container input-group"><span class="input-group-addon"><i class="glyphicon glyphicon-calendar"></i></span>'.
      DateRangePicker::widget([
         'name'  => 'ItemOrderSearch[created_at]',
         'pluginOptions'=>[ 
                  'locale'=>[
                  'separator'=>'to',
                  ],
          'opens'=>'right'
              ] 
          ]) . '</div>',
    'content'=>function($data){
               return Yii::$app->formatter->asDatetime($data['created_at'], "php:d-M-Y");
       }
    ]
    

3.Pick the date in your Controller parse date like

    $date = explode( 'to', $item['date']) // Temporary store into variable as an array
    // $date[0]  =>  12/07/2015 - from date
    // $date[1]  =>  12/10/2015 - to date

4.Pass it to your Model and execute query .

Share:
11,558
Pawan
Author by

Pawan

Web Developer

Updated on June 23, 2022

Comments

  • Pawan
    Pawan almost 2 years

    Well I can filter on any fields including the column from related fields, but I wonder how I can filter on date fields.

    One solution I came across is date-picker for filter, I have not tested this, but my requirement is little different.

    for example I have duplicated the datetime column in gridview and formatted it like

    [
        'attribute'=>'discharge_date',
        'format'=>['DateTime','php:M']
    ],
    

    So that the column will show only months.The column is showing the months correctly.

    Now I want to filter by month on this column. Any suggestion will be greatly appreciated. Thanks.

    I did try like this

    [
         'attribute'=>'discharge_date',
         'value'=>'discharge_date',
         'filter' => ['2015-01'=>'Jan','2015-02'=>'Feb','2015-03'=>'Mar'],
         'format'=>['DateTime','php:M']
    
      ],
    

    This works fine, but here the year is being hard-coded, which I don't want. I know this is not the proper way. Thanks