Yii2:使用kartik日期范围选择器在gridview中进行过滤

时间:2015-03-25 19:12:35

标签: php gridview filter yii2

我正在尝试使用Kartik Date Range选择器在gridview中进行过滤。

我的列date_time字段为discharge_date,小部件在gridview中显示正常,但过滤根本不起作用。

这是我在Gridview中的代码:

[
                'attribute'=>'discharge_date',
                'value'=>'discharge_date',                
                'filterType' => GridView::FILTER_DATE_RANGE,
                'filterWidgetOptions' =>([
                'model'=>$model,
                'attribute'=>'discharge_date',
                'presetDropdown'=>TRUE,                
                'convertFormat'=>true,                
                'pluginOptions'=>[                                          
                    'format'=>'Y-m-d',
                    'opens'=>'left'
                ]
            ])

            ],

我哪里错了?

Discharge Date

2 个答案:

答案 0 :(得分:6)

您需要在搜索模型中解析discharge_date过滤器值。作为示例,以下代码将获取过滤器值并将其拆分到破折号上,并将$ start_date和$ end_date添加到$ query字符串(即在之后添加它if if(!$ this-> validate()) {的):

if ( ! is_null($this->discharge_date) && strpos($this->discharge_date, ' - ') !== false ) {
    list($start_date, $end_date) = explode(' - ', $this->discharge_date);
    $query->andFilterWhere(['between', 'data_date', $start_date, $end_date]);
    $this->discharge_date = null;
}

答案 1 :(得分:1)

制作pluginEvent配置并修剪日期过滤器值的查询。 例如:

ModelSearch:

...
  $query->andFilterWhere(['like', 'name', $this->'name']); //this line is for reference

            if(isset ($this->only_date)&&$this->only_date!=''){ //you dont need the if function if yourse sure you have a not null date
              $date_explode=explode(" - ",$this->only_date);
              $date1=trim($date_explode[0]);
              $date2=trim($date_explode[1]);
              $query->andFilterWhere(['between','only_date',$date1,$date2]);
            }


        return $dataProvider;
...

专栏:

...
    [
      'attribute'=>'only_date',
      'options' => [
          'format' => 'YYYY-MM-DD',
          ],        
      'filterType' => GridView::FILTER_DATE_RANGE,
      'filterWidgetOptions' => ([       
        'attribute' => 'only_date',
        'presetDropdown' => true,
        'convertFormat' => false,
        'pluginOptions' => [
          'separator' => ' - ',
          'format' => 'YYYY-MM-DD',
          'locale' => [
                'format' => 'YYYY-MM-DD'
            ],
        ],
        'pluginEvents' => [
          "apply.daterangepicker" => "function() { apply_filter('only_date') }",
        ],
      ])
    ],
...