Using CJuiDatePicker for CGridView filter

We can use a CJuiDatePicker for a CGridView inline filter.

I hope the following sample code fragment will be enough for you.

Sample Code

$this->widget('zii.widgets.grid.CGridView', array(
	'dataProvider' => $model->search(),
	'filter' => $model,
	'afterAjaxUpdate' => 'reinstallDatePicker', // (#1)
	'columns' => array(
		...
		array(
			'name' => 'due_date',
			'filter' => $this->widget('zii.widgets.jui.CJuiDatePicker', array(
				'model'=>$model, 
				'attribute'=>'due_date', 
				'language' => 'ja',
				// 'i18nScriptFile' => 'jquery.ui.datepicker-ja.js', (#2)
				'htmlOptions' => array(
					'id' => 'datepicker_for_due_date',
					'size' => '10',
				),
				'defaultOptions' => array(  // (#3)
					'showOn' => 'focus', 
					'dateFormat' => 'yy/mm/dd',
					'showOtherMonths' => true,
					'selectOtherMonths' => true,
					'changeMonth' => true,
					'changeYear' => true,
					'showButtonPanel' => true,
				)
			), 
			true), // (#4)
		),
		...
	),
));

// (#5)
Yii::app()->clientScript->registerScript('re-install-date-picker', "
function reinstallDatePicker(id, data) {
        //use the same parameters that you had set in your widget else the datepicker will be refreshed by default
	$('#datepicker_for_due_date').datepicker(jQuery.extend({showMonthAfterYear:false},jQuery.datepicker.regional['ja'],{'dateFormat':'yy/mm/dd'}));
}
");
Note
  • Call CController::widget() with the third parameter set to 'true'. (#4)
  • Define 'afterAjaxUpdate' to call a javascript function that will reinstall the datepicker, because it will return to a plain textField each time the grid is updated by an ajax call. (#1) and (#5)
  • I had to define language specific 'i18nScriptFile' option manually when I first wrote this article. Setting 'language' option was not enough. But now, you don't need to do it. (#2)
  • Use 'defaultOptions' instead of 'options', otherwise you have to set those options again in the javascript function to reinstall the datepicker. (#3)

That's all. Have fun.

More to read
19 0
31 followers
Viewed: 59 106 times
Version: 1.1
Category: How-tos
Written by: softark
Last updated by: Kostas Apazidis (KonApaz)
Created on: Mar 26, 2012
Last updated: 6 years ago
Update Article

Revisions

View all history

Related Articles