How to create my own DataProvider in Yii using CDataProvider?

那年仲夏 提交于 2019-12-11 04:09:13

问题


I am in a situation like this below. I am fetching some data using CSqlDataProvider and its pagination (page size) which internally uses limit and offset. And after that I get

$rawData = $sqldp->getData();

Now I need to do some processing and adding additional data. So now I get

$modRawData = modification($rawData);

Now If I create one CArrayDataProvider to convert it into a Dataprovider so that I can use the CListView.

But My problem is here. Now I am unable to do Pagination. If I use CLinkPager its possible. But is there any other way so that I can create my own DATAPROVIDER and can handle the pagination while creating the dataProvider.


回答1:


You can instate CArrayDataProvider directly, like this:

$rawData=Yii::app()->db->createCommand('SELECT * FROM table')->queryAll(); //fetches array of associative arrays representing selected rows
            $dataProvider=new CArrayDataProvider($rawData, array(
                'id'=>'consumer', //this is an identifier for the array data provider
                'sort'=>false,
                'keyField'=>'id', //this is what will be considered your key field
                'pagination'=>array(
                    'pageSize'=>30, //eureka! you can configure your pagination from here
                ),
            ));

and you can use your $dataProvider in a CListView or CGridView now, like

$this->widget('zii.widgets.grid.CGridView',array(
    'id'=>'consumer-grid',
    'dataProvider'=>$data,
    'columns'=>array( // this array should include the attributes you want to display
        'id',
        'name',
        'additional_column_1',
    ),

));

The potential of CArrayDataProvider can match meet up your standard needs without much work, altough it might require some additional work for filtering and sorting in some cases. You can check it's documentation page to find out more.




回答2:


At last I got the answer. And yes I can create my custom DataProvider by extending CDataProvider. But I needed to only implement three functions

fetchData, fetchKeys, calculateTotalItemCount

And lastly you need to write your own logic into fetchData as you want.



来源:https://stackoverflow.com/questions/23739588/how-to-create-my-own-dataprovider-in-yii-using-cdataprovider

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!