Cactivedataprovider With Cgridview Filter

I’ve spent hours reading forums etc. trying to see how to use a filter in CGridview when the dataProvider comes from CActiveDataProvider.

It’s so easy when you just say:

‘dataProvider’=>$model->search(),

‘filter’=>$model,

I don’t understand why it doesn’t work when the data provider is created from CActiveDataProvider. Surely it is possible, but the forums that talk about this seem too complicated and say different things. If someone could please post a very simple example (just one column grid even) of how to set this up I (and many others I expect) would be incredibly grateful!

Hi tommy,

Have you tried this wiki?

http://www.yiiframework.com/wiki/381/cgridview-clistview-and-cactivedataprovider

I hope it will give you the basic concepts of CActiveDataProvider with CGridView.

Yes I looked at that and there is some good information there but the examples were all for where the dataProvider is $model->search() and filter is $model. After some trial and error I came up with a basic example that allows the filter function of Cgridview to work when using CActiveDataProvider:

In the Controller:


        

public function actionFroggy() { 

$modelc=new Callee('search');

$modelc->unsetAttributes();  

if(isset($_GET['Callee'])) $modelc->attributes=$_GET['Callee'];

$this->render('froggy',array(

'modelc'=>$modelc,

));

}



And in the view:




    $criteria = new CDbCriteria;

    $criteria->compare('recipient', $modelc->recipient, true);

    $criteria->addCondition("id not in (select calleeId from xref where callgroupId = 22)");

    $dataProvider=new CActiveDataProvider('Callee', array('criteria'=>$criteria));

 

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

            'dataProvider'=>$dataProvider,

            'filter'=>$modelc,

            'columns'=>array(

                'recipient',

                array(

                    'class'=>'CButtonColumn',

                ),

            ),

        ));  



Note: the line that contains the $_GET data in the controller method has to be there. I got off course because I had thought that it was only needed for form submissions, but the CGridView filter doesn’t work without it! Also the bit about the “criteria->compare(…)” has to be there for the filter to work.

I hope this extremely simple example provides a starting point for someone else like me starting on the road to Yii mastery.