How to filter CGridView with From Date and To Date datepicker

This artical is related to allow user to filter CGridView with date range using datepicker on submit button. Here I use Yii Cookie to preserve date in datepicker textbox after submitting the form.

Step 1 : Lets insert below code in your view part where required I create one form for submit the dates ( from_date & to_date )

View
<?php $form=$this->beginWidget('CActiveForm', array(
	'id'=>'page-form',
	'enableAjaxValidation'=>true,
)); ?>

<b>From :</b>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
    'name'=>'from_date',  // name of post parameter
	'value'=>Yii::app()->request->cookies['from_date']->value,  // value comes from cookie after submittion
     'options'=>array(
        'showAnim'=>'fold',
		'dateFormat'=>'yy-mm-dd',
	),
    'htmlOptions'=>array(
        'style'=>'height:20px;'
    ),
));
?>
<b>To :</b>
<?php
$this->widget('zii.widgets.jui.CJuiDatePicker', array(
    'name'=>'to_date',
	'value'=>Yii::app()->request->cookies['to_date']->value,
     'options'=>array(
        'showAnim'=>'fold',
		'dateFormat'=>'yy-mm-dd',

    ),
    'htmlOptions'=>array(
        'style'=>'height:20px;'
    ),
));
?>
<?php echo CHtml::submitButton('Go'); ?> // submit button
<?php $this->endWidget(); ?>

// BELOW THIS YOUR CGridView code...

Insert below code in controller

Controller
unset(Yii::app()->request->cookies['from_date']);  // first unset cookie for dates
unset(Yii::app()->request->cookies['to_date']);
		
$model=new XyzModel('search');  // your model
$model->unsetAttributes();  // clear any default values
		
  if(!empty($_POST))
  {
    Yii::app()->request->cookies['from_date'] = new CHttpCookie('from_date', $_POST['from_date']);	// define cookie for from_date
    Yii::app()->request->cookies['to_date'] = new CHttpCookie('to_date', $_POST['to_date']);
    $model->from_date = $_POST['from_date'];
    $model->to_date = $_POST['to_date'];
}

Now code for model part

Add two public variable in your model class

Model
public $from_date;
public $to_date;

now mark them as safe attribute

... ...  from_date, to_date', 'safe', 'on'=>'search'),

now just put below code in your search function in model class,

if(!empty($this->from_date) && empty($this->to_date))
		{
			$criteria->condition = "date >= '$this->from_date'";  // date is database date column field
		}elseif(!empty($this->to_date) && empty($this->from_date))
		{
			$criteria->condition = "date <= '$this->to_date'";
		}elseif(!empty($this->to_date) && !empty($this->from_date))
		{
			$criteria->condition = "date  >= '$this->from_date' and date <= '$this->to_date'";
		}
Demo Image

Image and this is it as you can filter from date range ... .. .