zoukankan      html  css  js  c++  java
  • Using filters with CGridView and CArrayDataProvider

    Using filters with CGridView and CArrayDataProvider

    23 followers

    Using filters on CGridView with CActiveDataProvider is easy, but with CArrayDataProvider it is a bit tricky.

    To use the filters you have to create a separate model class. I used some code from the following forum topic: link

    Here is some example code:

    Model

    Copy and include this class into your application.

    /**
     * Filterform to use filters in combination with CArrayDataProvider and CGridView
     */
    class FiltersForm extends CFormModel
    {
        public $filters = array();
     
        /**
         * Override magic getter for filters
         */
        public function __get($name)
        {
            if(!array_key_exists($name, $this->filters))
                $this->filters[$name] = null;
            return $this->filters[$name];
        }
     
        /**
         * Filter input array by key value pairs
         * @param array $data rawData
         * @return array filtered data array
         */
        public function filter(array $data)
        {
            foreach($data AS $rowIndex => $row) {
                foreach($this->filters AS $key => $value) {
                    // unset if filter is set, but doesn't match
                    if(array_key_exists($key, $row) AND !empty($value)) {
                        if(stripos($row[$key], $value) === false)
                            unset($data[$rowIndex]);
                    }
                }
            }
            return $data;
        }
    }

    Controller

    // Create filter model and set properties
    $filtersForm=new FiltersForm;
    if (isset($_GET['FiltersForm']))
        $filtersForm->filters=$_GET['FiltersForm'];
     
    // Get rawData and create dataProvider
    $rawData=User::model()->findAll();
    $filteredData=$filtersForm->filter($rawData);
    $dataProvider=new CArrayDataProvider($filteredData);
     
    // Render
    $this->render('index', array(
        'filtersForm' => $filtersForm,
        'dataProvider' => $dataProvider,
    ));

    View

    $columns = array(
        array(
            'header'=>CHtml::encode('Name'),
            'name'=>'username',
        ),
        array(
            'header'=>CHtml::encode('Organisation'),
            'name'=>'organisation',
        ),
    );
     
    $this->widget('zii.widgets.grid.CGridView', array(
        'id'=>'area-grid',
        'dataProvider'=>$dataProvider,
        'columns'=>$columns,
        'filter'=>$filtersForm,
    ));
  • 相关阅读:
    Pearls POJ 1260 DP
    The Cow Lexicon DP
    矩形嵌套
    POJ 3061 Subsequence 尺取
    动物统计加强版 Trie 树
    codevs 1422 河城荷取
    cogs 944. [東方S3] 藤原妹红
    codevs 2830 蓬莱山辉夜
    cogs 998. [東方S2] 帕秋莉·诺蕾姬
    cogs 920. [東方S1] 琪露诺
  • 原文地址:https://www.cnblogs.com/xiongsd/p/3062823.html
Copyright © 2011-2022 走看看