Cgridview Filter (Sql Query)

Hi,

Long day, brain… not… working…

I need to filter results in the zii.widgets.grid.CGridView (soon to be Bootstrap) so that it only shows rows where the data in column ‘lead_type’ is equal to ‘1’ (and i’ll also us it again on another grid where it equals ‘0’).

Presumables it’s something i add to the Models search function… using CActiveDataProvider…

Any snippets to borrow?

I didn’t get the problem clearly… but I assume that your question is about how to filter your gridview on that ‘lead_type’ column, then:

do you have this field in your search function?

you should have something like this:




	public function search()

	{

		$criteria=new CDbCriteria;


		$criteria->compare('lead_type',$this->lead_type);  // this is essential

		$criteria->compare( /* other parameters */ );


		return new CActiveDataProvider($this, array(

			'criteria'=>$criteria,

		));

	}



alternatively, if your question is about populating a gridview at first with a custom filter, and not with all the db data, this should help:

so, we want it to always load data with ‘lead_type’ = someSpecificValue .again, we need to edit search function, lets name it customSearch:




        public function customSearch($defaultValue = null)

        {

                $criteria=new CDbCriteria;


                $criteria->compare('lead_type',$defaultValue);  // again, this is essential

                $criteria->compare( /* other parameters */ );


                return new CActiveDataProvider($this, array(

                        'criteria'=>$criteria,

                ));

        }



that’s it. then, when you call this function in your view, you should pass your desired value to it.




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

	'id'=>'yourModel-grid',

	'dataProvider'=>$model->customSearch( $yourDesiredValue ),

	'filter'=>$model,

        ...



using this approach, your grid view by default will load filtered data, not all of them.

Hi Hesam Khaki,

Thank you for your help, and thanks again for offering two examples!

Basially, I think your second approach is what i need, to set the grid view to only show rows from the database where ‘lead_type’ == ‘0’ (and 1 on another view so will just change the variable in the function you provided.)

I get this error though, so will work out whats happeneing

UPDATE

I was putting it in the Controller, not the Model… now its working, great!