Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

DateRange as GridView filter disappears after pjax request #48

Closed
fabioaccetta opened this issue Aug 18, 2015 · 15 comments
Closed

DateRange as GridView filter disappears after pjax request #48

fabioaccetta opened this issue Aug 18, 2015 · 15 comments

Comments

@fabioaccetta
Copy link

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
Copy link

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
Copy link

marcoadasilvaa commented May 15, 2016

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
Copy link

@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
Copy link

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
Copy link

I've got the same problem...

@xavsio4
Copy link

xavsio4 commented Sep 22, 2016

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
Copy link

@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
Copy link

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
Copy link

wcoc commented May 22, 2017

same problem here.

@zoolanders49
Copy link

@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
Copy link
Owner

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

@bariew
Copy link

bariew commented Sep 23, 2017

#72
Hi guys, I think this has already been explained in #72

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

@kartik-v
Copy link
Owner

kartik-v commented Sep 23, 2017

Folks I reviewed this issue.

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

  • OPTION 1: for GridView it is recommended to use the FILTER_DATE_RANGE to set your filter
  • OPTION 2: if manually rendering the widget set pjaxContainerId to the pjax container identifier in which the widget is getting rendered to auto reinitialize.

Closing this.

@searce06
Copy link

searce06 commented Aug 2, 2018

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
Copy link

andvis commented May 2, 2019

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests