How to filter the search results as a combination of checkboxes and dropdown in Yii? I have some categories as checkboxes and budget as dropdown that is listing from database. WIth multiple checkboxes checked and selecting a value from dropdown, how can I filter out the search results.. Is there any better way ?? (My requirement is like in this link. http://www.ebay.in/sch/i.html?_from=R40&_sacat=0&_nkw=pendrives&rt=nc&LH_FS=1 )
2 Answers
I recommend to use a search model. This could look like this:
class SearchProducts extends CFormModel
{
public $minPrice;
public $maxPrice;
public $categories;
// Add a public property for each search form element here
public function rules()
{
return array(
// You should validate your search parameters here
array('minPrice,maxPrice,categories', 'safe'),
);
}
public function search()
{
$criteria = new CDbCriteria;
if(!empty($this->minPrice))
$criteria->addCondition('price > '.(int)$this->minPrice);
if(!empty($this->maxPrice))
$criteria->addCondition('price < '.(int)$this->maxPrice);
if(!empty($this->categories))
$criteria->addInCondition('category_id', $this->categories);
// Add more conditions for each property here
return new CActiveDataProvider('Product', array(
'criteria' => $criteria,
// more options here, e.g. sorting, pagination, ...
));
}
}
In your controller you create a new instance of the search form and assign search variables as usual:
public function actionProducts()
{
$searchModel = new ProductSearch();
if(isset($_POST['ProductSearch']))
$searchModel->attributes = $_POST['ProductSearch'];
$this->render('products', array(
'searchModel' => $searchModel,
));
}
Finally in your view you can now render
- A regular Yii form for
$searchModel
properties which will be your search filter form - A
CListView
or aCGridView
where you set theprovider
to$searchModel->search()
which will be your search results.
For the checkboxes you'd use a checkBoxList:
<?php $this->formCheckBoxList($model, 'categories[]', Category::opts()) ?>
Note the []
which indicates that this should be posted as array. For convenience i usually also implement a static opts()
method in some models, which returns a list of id=>name
that you can use for dropDownList or checkBoxList options.
This is only the basic pattern. You can easily extend it to create really powerful search forms and result list. Just always keep in mind that you should keep all search related data in another model.

- 8,428
- 5
- 35
- 62
-
I need dynamic updations in listview on clicking the categories.How can I implement this ? – anu Apr 24 '13 at 08:33
try this extension: ddautofilter https://bitbucket.org/jwerner/yii-ddautofilter/overview

- 5,455
- 53
- 53