Reputation: 3864
I am trying to use the Kartik Date Range picker for filter in gridview.
I have a column date_time field as discharge_date
, the widget is showing fine in the gridview but the filtering is not working at all.
This is my code in the 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'
]
])
],
Where I am going wrong?
Upvotes: 4
Views: 12767
Reputation: 943
make a pluginEvent configuration and trim your query for the date filter value. ex:
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;
...
column:
...
[
'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') }",
],
])
],
...
Upvotes: 2
Reputation: 348
You need to parse the discharge_date filter value in your Search model. As an example the following code will take the filter value and split it on the dash and add the $start_date and $end_date to the $query string (i.e. add it after 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;
}
Upvotes: 8