yII2:日期过滤器如何在Gridview中

Paw*_*wan 3 php gridview filter yii2

好了,我可以过滤任何字段,包括相关字段中的列,但是我想知道如何过滤日期字段。

我遇到的一个解决方案是过滤器的日期选择器,我没有测试过,但是我的要求没有什么不同。

例如,我已经datetime在gridview中复制了该列,并将其格式化为

[
    'attribute'=>'discharge_date',
    'format'=>['DateTime','php:M']
],
Run Code Online (Sandbox Code Playgroud)

因此该列将仅显示月份。该列正确显示了月份。

现在,我想按月在此列上进行过滤。任何建议将不胜感激。谢谢。

我确实尝试过

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

  ],
Run Code Online (Sandbox Code Playgroud)

效果很好,但是这里是硬编码的年份,我不希望这样。我知道这不是正确的方法。谢谢

小智 5

您可以使用kartik日期范围选择器:

1.检查一下:https : //github.com/kartik-v/yii2-date-range

实作

1.您认为:使用kartik \ daterange \ DateRangePicker;

2.如果使用网格视图

  • 将此代码添加到属性中

    [
     '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");
       }
    ]
    
    Run Code Online (Sandbox Code Playgroud)

3,在控制器解析日期中选择日期,例如

    $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
Run Code Online (Sandbox Code Playgroud)

4.将其传递给您的模型并执行查询。