2013-04-02 66 views

回答

1

我建議使用搜索模式。這可能是這樣的:

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, ... 
     )); 
    } 
} 

在你的控制器創建搜索表單的一個新實例,並指定搜索變量和往常一樣:

public function actionProducts() 
{ 
    $searchModel = new ProductSearch(); 

    if(isset($_POST['ProductSearch'])) 
     $searchModel->attributes = $_POST['ProductSearch']; 

    $this->render('products', array(
     'searchModel' => $searchModel, 
    )); 
} 

最後,在你看來,你現在可以渲染

  1. $searchModel屬性的常規Yii表格將成爲您的搜索過濾器形式
  2. A CListViewCGridView,您將provider設置爲$searchModel->search(),這將是您的搜索結果。

對於複選框你使用的CheckBoxList:

<?php $this->formCheckBoxList($model, 'categories[]', Category::opts()) ?> 

注意[]這表明,這應該是張貼陣列。爲了方便起見,我通常還在某些模型中實現了靜態opts()方法,該方法返回可用於dropDownList或checkBoxList選項的id=>name的列表。

這只是基本模式。您可以輕鬆擴展它以創建真正強大的搜索表單和結果列表。請始終記住,您應該將所有搜索相關數據保留在另一個模型中。

+0

如何能將它的複選框來完成? – anu

+0

查看更新的答案。 –

+0

我需要在列表視圖中點擊類別動態更新。如何實現這個? – anu