Hi All,
I have a page where I show a “report” of data using CGridView. The user can filter the data through using some dropdown fields at the top of the report. (Filters include a date range, for example.) When the report filter(s) are set and the form is submitted, I grab the filter values, load them into a CDbCriteria object, then use the criteria object to make a CActiveDataProvider object. I also use a CSort object to define which columns are sortable. However, whenever I click on a column header to sort by that column, my criteria filters are lost, and the report returns to its default state without the filters values added to the criteria. Here’s an example of my code:
//* controller
class MyController extends Controller
{
public function actionReport()
{
//* set default filter values
$startDate = date('Y-m-01',strtotime('-1 month'));
$endDate = date('Y-m-d');
//* get filter values from form post
if(isset($_POST['filter']))
{
$startDate = $filters['start_date'];
$endDate = $filters['end_date'];
}
//* set up criteria object based on filter values
$criteria = new CDbCriteria;
$criteria->addCondition('collection_date BETWEEN :startdate AND :enddate');
$criteria->params = array(
':startdate' => $startDate,
':enddate' => $endDate,
);
//* set sort options
$sort = new CSort;
$sort->attributes = array(
'field_one',
'field_two'.
);
$sort->defaultOrder = 'field_one DESC';
$sort->multiSort = true;
//* create data provider
$dataProvider=new CActiveDataProvider('Report', array(
'criteria'=>$criteria,
'sort'=>$sort,
'pagination'=>array(
'pageSize'=>50,
),
));
//* render view
$this->render('report',array(
'dataProvider' => $dataProvider,
));
}
}
//* view
....
<?php
$this->widget('zii.widgets.grid.CGridView', array(
'dataProvider'=>$dataProvider,
'columns'=>array(
'field_one',
'field_two',
)
));
?>
I think that this has something to do with the fact that my action code only applies the user-defined filter values to the criteria if the form was posted. In the case of a sort, the action is run via ajax and without the form being posted. I’m just not sure of the best way to go about fixing the issue. Can I append filtered parameters to my sort column headers so that the filter data gets passed through with the ajax sort call? What’s the best way to solve this problem – I’m sure I’m not the first to need to figure this out, but I haven’t found anything in the forums yet. Thanks in advance for any assistance!