kartik-v / yii2-date-range

A Date Range Picker for Bootstrap useful for reports and filtering.
http://demos.krajee.com/date-range
Other
92 stars 80 forks source link

DateRange as GridView filter disappears after pjax request #48

Closed fabioaccetta closed 7 years ago

fabioaccetta commented 9 years ago

I have an Invoice model (with its InvoiceSearch one extending it) having a delivery_date field. I'm trying to use the DateRangePicker widget to filter my yii\grid\GridView. DateRangePicker configuration is:

$daterange = [
    'model' => $invoiceSearch,
    'attribute' => 'delivery_date',
    'convertFormat' => false,
    'pluginOptions' => [
        'format' => 'YYYY-MM-DD',
    ],
];

so I use it in my column definition:

[...]
[
    'attribute' => 'delivery_date',
    'filter' => DateRangePicker::widget($daterange),
],
[...]

Widget works only the first time (i.e. calendar appears and after date selection the pjax request starts), but after the response replaces the grid view with the filtered one, date range picker is no more shown. Inspecting the pjax response, there is no new daterangepicker_<hash> inside the html, while the input field has a new config data reference instead.

P.S.: if I replace config with this:

$daterange = [
    'model' => $invoiceSearch,
    'attribute' => 'delivery_date',
    'convertFormat' => true,
    'pluginOptions' => [
        'format' => 'php:Y-m-d',
    ],
];

widget dates are not correctly parsed and appear like this: p12p:2015-08-18 instead of 2015-08-18 (always disappearing after the first request as before).

Do I miss something?

cicsolutions commented 8 years ago

I can't say for sure, but you probably need to update your search model to account for the value from the datepicker in your database query. The value submitted from the datepicker widget needs to be parsed so you can compare the start date and end date of the range to your delivery_date field. Something like the following probably needs to be added to your search model.

$query->andFilterWhere([
    'between', 'delivery_date', $range_start, $range_end),
]);
marcoadasilvaa commented 8 years ago

Please, do you send de InvoiceSearch or check it

    //this is attribute of filter input:
    public $dealerAvailableDate;

...

if (!is_null($this->dealerAvailableDate) && 
            strpos($this->dealerAvailableDate, ' - ') !== false ) {
            list($start_date, $end_date) = explode(' - ', $this->dealerAvailableDate);
            $query->andFilterWhere(['between', 'date(dealer_available.date)', $start_date, $end_date]);
        }

View:


[
                            'label' => Yii::t('app', "Appointment Date"),
                            'attribute' => 'dealerAvailableDate',
                            'value' => 'dealerAvailable.date',
                            'format' => 'datetime',
                            'filter' => DateRangePicker::widget([
                                'model' => $searchModel,
                                'attribute' => 'dealerAvailableDate',
                                'convertFormat' => true,
                                'pluginOptions' => [
                                    'locale' => [
                                        'format' => 'Y-m-d'
                                    ],
                                ],
                            ]),
                        ],
msankar1991 commented 8 years ago

@markmarco16

I've used your above solution but it not working to me. I've used the following way to achieve this.

use kartik\daterange\DateRangePicker;

...........

[
    'label' => Yii::t('app', "Date"),
    'attribute' => 'dealerAvailableDate',
    'value' => 'customer_measurement.created_date',
    'format' => 'datetime',
    'filter' => DateRangePicker::widget([
        'model' => $searchModel,
        'attribute' => 'dealerAvailableDate',
        'convertFormat' => true,
        'pluginOptions' => [
            'locale' => [
                'format' => 'Y-m-d'
            ],
        ],
    ]),
],

...............

 if (!is_null($this->dealerAvailableDate) && 
    strpos($this->dealerAvailableDate, ' - ') !== false ) {
    list($start_date, $end_date) = explode(' - ', $this->dealerAvailableDate);
    $query->andFilterWhere(['between', 'date(customer_measurement.created_date)', $start_date, $end_date]);
}
akorinek commented 8 years ago

I've got the same problem, it works when I set the 'pjax' value to false in the grid, otherwise after a pjax reload, the daterange does not initialize. Any workarounds for this?

tigrasti commented 8 years ago

I've got the same problem...

xavsio4 commented 8 years ago

Hi, I have the same problem. The binding of the daterangepicker is lost after pjax. I then set 'pjax'=>false...response still acceptable even if not elegant.

Also i tried this but it generated a bad side effect (but it proves the bind loose after pjax refresh). $this->registerJs(' $(document).on("pjax:complete", function() { $("#expensesearch-date_expense").daterangepicker(); });', View::POS_READY);

playwolf719 commented 7 years ago

@kartik-v Same Issue here. It seems that there is problem between pjax and date-range. There is a redirect after I select date range, it returns to the default value.

playwolf719 commented 7 years ago

Maybe you should use DatePicker instead. Check this out http://dennis2society.de/yii-2-redirect-on-krajee-datepicker-changedate-event Use "GET" parameter I solve my problem. @fabioaccetta

wcoc commented 7 years ago

same problem here.

zoolanders49 commented 7 years ago

@kartik-v hello, I have the same problem : the widget work only on first load. Please say if there is a solution to this issue. I add "filterType" => Gridview::FILTER_DATE_RANGE, in the gridview but this don't help me.

Thanks

kartik-v commented 7 years ago

Will need to check and figure out for this plugin for a pjax scenario when I get time.

bariew commented 7 years ago

72

Hi guys, I think this has already been explained in https://github.com/kartik-v/yii2-date-range/issues/72

You just need to set widget 'pjaxContainerId' the same as your Pjax id It works for me on 1.6.8

kartik-v commented 7 years ago

Folks I reviewed this issue.

A mentioned in this comment in #72 and as bariew mentioned

Closing this.

searce06 commented 6 years ago

Hola dejare mi respuesta en español porque no soy bueno en el ingles. Bueno igual tuve mucho problemas pero el error que me aparece a mi era simple de solucionar tengo el siguiente codigo en la carpeta modelo en el archivo ServicioSearch

$query->andFilterWhere(['like', 'estado', $this->estado]); $timestamp_since = explode(";", $this->fecha, 2); if ($this->fecha != null) {

        $a = $timestamp_since[0];
        $b = $timestamp_since[1];

        $query->andFilterWhere(['between','fecha',$a,$b]);

     }

y este codigo pertenece al gridView:

[ 'attribute' => 'fecha',

        'value' => function ($data) {
             $nueva=explode(":",$data->fecha);
            return $nueva[0].":".$nueva[1];
        },

        'filter' => DateRangePicker::widget([
            'model' => $searchModel,
            'attribute' => 'fecha',
            'convertFormat' => true,
            'presetDropdown'=>true,

            'pluginOptions' => [
                'locale' => [
                    'format' => 'Y-m-d H:i',
                    'separator' => ';',
                    'opens' => 'left'
                ]
            ]
        ])

    ],

Todo esto me funciona perfectamente y no tuve que meterme al kartik o al js, pero me costo darme cuenta que tenia que sacar la fecha del siguiente codigo (yo la comente como podrán ver en la siguiente imagen)

$query->andFilterWhere([ 'nFactura' => $this->nFactura, //'fecha' => $this->fecha,(-------------aqui------------------) 'FK_tipoServicio' => $this->FK_tipoServicio, 'nGarantia' => $this->nGarantia, 'nServicioMantencion' => $this->nServicioMantencion, 'detalle' => $this->detalle, ]); este codigo debe estar en ServicioSearch.

Espero que le sirva, se que este post es del 2015 y el ultimo es del 2017, pero espero que si encuentran este post le ahorre trabajo de alguna manera saludos a todos y suerte en todo!.

andvis commented 5 years ago

On my application happen a strange thing. I'm using kartik\daterange\DateRangePicker in a kartik\grid\GridView.

Here is the general settings:

'dataProvider' => $dataProvider,
        'filterModel' => $searchModel,
        'options'=>['class'=>'pntmd-gridview-order','id'=>'pntmd-gridview-order'],
        'striped'=>false,
        'bordered'=>true,
        'hover'=>true,
        'responsive'=>true,
        'resizableColumns'=>false,
        //'persistResize'=>true,
        'responsiveWrap' => false,
        //'pjax'=>true,
        'pjaxSettings'=>[
                'loadingCssClass'=>false,
                'options'=>[
                    'id'=>'pjax-pntmd-gridview-ordini',
                ]
        ] 
```.... etc etc

Here is a column setting:

[ 'attribute' =>'tm_insert', 'format' => 'html', 'options'=>['style'=>'font-size:11px'], 'value'=>function($model){ $oggi = date('d-m-Y'); $date = date('d-m-Y', strtotime($model->tm_insert));

                    if($date === $oggi) $date = 'Oggi '.date('H:i', strtotime($model->tm_insert));
                    else $date = date('d-m-Y H:i', strtotime($model->tm_insert));

                    return $date;
                },          
                'filter' => DateRangePicker::widget([
                    'model' => $searchModel,
                    'presetDropdown'=>false,
                    'attribute' => 'tm_insert',
                    'convertFormat' => true,
                    'pjaxContainerId'=>'pjax-pntmd-gridview-ordini',
                    'pluginOptions' => [
                        'separator'=>' - ',
                        'locale' => [
                            'format' => 'd-m-Y'
                        ],
                    ],
                ]).'<a href="#" id="reset-tm_insert">reset</a>',

        ],


The strange behavior is that starting to the second time, the page falls in an infinite loop. It recharge continusly the page freezing so the application. Any explain on that.