Nice Feature In Cactivedataprovider

<Scenario>: I want to add a pie chart to a report, and the data based on search result. For example, my search results return all employees from one department, and I want to display numbers of managers vs all employees in a pie chart. This needs we get exactly number of managers from current search result.

Of course you can do a foreach loop to check each manager flag, if the number of employee is over thousand, then you will feel the page is not running fast as you expected.

Thanks to Yii CActiveDataProvider, we can add criteria to exist condition via following steps:

In you views/admin.php, you should have below code, which $model->search() should return CActiveDataProvider of a model.




$this->widget('zii.widgets.grid.CGridView', array(

..

'dataProvider'=>$model->search(),

..



Then I added my code above CGridView widgets:




$Employees=$model->search();

$totalEmployeesCount=$Employees->getTotalItemCount();

//then get count criteria, this is new feature in 1.1.14, if you are not use this release or above,

//try getCriteria, no any problem.

$criteria=$dataProvider->getCountCriteria();

//add you new conditions

$criteria->addCondition('managerFlag IS NOT NULL');

//apply new conditions

$Employees->setCountCriteria($criteria);

//True means it will refresh the data, if you tracking log is turned on, you will see this function call triggered to run a query with your new condition

$ManagerCount=$dEmployees->getTotalItemCount(TRUE);

//Now you can add your values into pie chart, or whatever



This method is much faster than you use foreach loop when results is big.

Hope it can bring some new idea if you have same situation.

/* Moved to Tips, snippets and tutorials */