CActiveDataProvider With Custom Query

Hi i used CActiveDataProvider everytime to retrieve the data for CGridView.But one of my project needed custom query in criteria and have to show the result in CGridView. During that time i found MyActiveDataProvider concept with extends of CActiveDataProvider. I applied that concept and working fine for me. I added that source code for you. I think it may helpful on sometime.

Component MyActiveDataProvider

Please add this class inside “protected/components”.

class MyActiveDataProvider extends CActiveDataProvider {

    protected function calculateTotalItemCount() {
        if ($baseCriteria!==null)
                $baseCriteria=clone $baseCriteria;
        //You can get real records count only in this way (when you use JOIN and GROUP BY)
        return $count;

Custom Query In Model

In this model i added the “MyActiveDataProvider” instead of “CActiveDataProvider” with custom select query.

    public function searchbygroup()
		$criteria=new CDbCriteria;       
		//custom query
        $criteria->select=array('*,concat(documentid,"_",userid) as groupid,count(documentid) as downloadcount');
		//Add Different Condition
        $criteria->addCondition("documentid IN ('$this->documentid')");
        // group by , if need
		//return new CActiveDataProvider($this, array(			'criteria'=>$criteria,		));
        return new MyActiveDataProvider($this,array('criteria'=>$criteria));

CGridview List Of Group Search

In this gridview i retrieved the data from custom query of CActiveDataProvider(via MyActiveDataProvider) and displayed in gridview result successfully.

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

		// columns from relation model
		// column from custom query
)); ?>

Leave a Reply

Your email address will not be published. Required fields are marked *