Filter By Looked Up Value In Cgridview

Hi,

My early days of Yii. Have searched and can’t find any clues on this hence post. I have modified the admin.php layout to lookup values from a couple of related tables as follows


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

	'id'=>'silo-grid',

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

	'filter'=>$model,

	'columns'=>array(

		'id',

		array(

			'name'=>'silo_id',

			'value'=>'$data->silo->name',

			'header'=>'Parent',

		),

		'name',

		array(

			'name'=>'silo_type',

			'value'=>'$data->siloType?$data->siloType->type:"no silo type"',

		),

		array(

			'class'=>'CButtonColumn',

		),

	),

)); ?>

This is great and all works … apart from the fact that the filter fields are still looking up the numerical values rather than the text values (e.g. I want to filter on a text ‘description’ rather than the UID that represents that description).

How do I go about changing this?

Thanks

The code you posted is for the display.

In this case your CActiveDataProvider object along with the search criteria is created and returned by the search() method of the $model object.

If you look in your model for ‘public function search()’ you’ll find the search criteria and you can edit it to taste.

Look for something like this:




		$criteria->compare('silo_type',$this->silo_type,true);



And try changing it to something like this:




		$criteria->compare('siloType.type',$this->silo_type,true);



Since you used ‘name’=>‘silo_type’ in the column the contents of the filter from the grid for that column will be available in the model as $this->silo_type. You would now be using the user submitted value of silo_type to compare to the value or a related model.

For the purposes of this search the value of silo_type no longer has to be a valid value for the silo_type column since you are now comparing the user submitted value to the value of the type column in the related siloType model.

I thought I would add that you can also create new attributes in your model that you can use in the CGridView filter. Just in case you want to allow searching by all values in your model as well as values in your related model. Just remember to add the new properties you create into the rule for the search scenario so that they are marked as safe. Otherwise the user submitted values of any of these new properties you create would be ignored when the data is massively assigned. If you don’t understand this yet, don’t worry about it. I just wanted you to know that allowing the search to include criteria for a related model doesn’t mean that you have to sacrifice a column from the model doing the search.