Broken search when using relations

Hello, I have used gii crud generator to generate the admin view.

In CGridview I have used ‘category.name’ to display a relation between to tables. When I use relations the search-functionality doesn’t work, is there an easy way to handle this?

Thanks

Hello.

Yes: http://www.yiiframework.com/wiki/281/searching-and-sorting-by-related-model-in-cgridview

Cheers :)

Thanks! Works great.

Is there a simple way to use the same method in the advanced search-field?

Glad I could help.

In advanced search, there’s nothing special to do if you use Gii. All you need is changing maybe the type of attributes’ inputs for the related models in the search form.

Gii generates all input fields as text fields. For instance, taking your category.name example, I suppose you have a Category model, and categoryId is the foreign key. So you’ll have something like that in _search.php form:


<?php echo $form->label($model, 'categoryId'); ?>

<?php echo $form->textField($model, 'categoryId'); ?>

But of course you don’t want the end users typing ids, but instead, choosing from, say, a dropdown:


<?php echo $form->label($model, 'categoryId'); ?>

<?php echo $form->dropDownList($model, 'categoryId',

                               CHtml::listData(Category::model()->findAll(array('order'=>'name')), 'id', 'name'),

                               array('empty' => 'Please select a category')

                               ); ?>

Thanks alot!