Yii paging instance usage

Source: Internet
Author: User
Tags api manual comments php foreach yii advantage

First: CListView paging for object-based data paging

The code is as follows: Copy code

[Controller]

Public function actionAjax (){

$ Criteria = new CDbCriteria ();

// $ Criteria-> order = 'news _ id DESC ';

$ Criteria-> condition = 'User _ id = 1 ';

  

$ DataProvider = new CActiveDataProvider ('news', array (

'Pagination' => array (

'Pagesize' => Yii: app ()-> params ['pagesize'],

'Pagevar '=> Yii: app ()-> params ['pagevar'],

),

'Criteria '=> $ criteria,

));

  

  

$ This-> render ('View', array (

'Dataprovider' => $ dataProvider,

));

    }
[View]

<! --? Php

$ This ---> widget ('zii. widgets. Clistview', array (

'Dataprovider' => $ dataProvider, // data

'Itemview' => '_ view', // displayed Template

'Id' => Yii: app ()-> controller-> id,

'Itemstagname' => 'u ',

'Ajaxvar '=> '', // The default value is page or ajax.

'Htmlopexception' => array ('class' => Yii: app ()-> controller-> id ),

'Loadingcssclass '=> 'loading', // The default value is list-view-loading.

// 'Template' => '{summary} {sorter} {items} {pager}', // display order

// 'Ajaxupdate' => false, // whether ajax pagination is false or the container id displayed by page

// 'Beforeajaxupdat' => 'Before _ ajax_update', // The callback function is completed in common. js.

// 'Afterajaxupdate' => 'after _ ajax_update ',

'Emptytext' =>'

<DIV class = "alert-waning">

No data!

</DIV>

', // Content displayed when no data exists

'Pagercssclass '=> 'pagination', // paging class

'Pager' => array (

'Selectedpagecssclass '=> 'active', // class on the current page

'Hidenpagecssclass '=> 'disabled', // class of the disabled page

'Header' => '', // the content displayed before the page

'Maxbuttoncount' => 10, // display the number of pages

'Htmlopexception' => array ('class' => ''),

'Firstpagelabel '=> 'homepage ',

'Nextpagelabel '=> 'next page ',

'Prevpagelabel '=> 'previous page ',

'Lastpagelabel '=> 'Last page ',

),

));

  


?>


2nd types: CLinkPager for array-based data paging

The code is as follows: Copy code


[Controller]


Public function actionIndex (){

  

$ Criteria = new CDbCriteria ();

$ Criteria-> order = 'news _ id DESC ';

$ Criteria-> condition = 'User _ id = 1 ';

  

$ Count = News: model ()-> count ($ criteria );

$ Pages = new CPagination ($ count );

  

$ Pages-> pageSize = 10;

$ Pages-> applyLimit ($ criteria );

$ List = News: model ()-> findAll ($ criteria );

  

$ This-> render ('index', array ('list' => $ list, 'Pages '=> $ pages ));

    }

 

 


[View]

 

 

<UL>

<! --? Php foreach ($ list as $ item ):? -->

<LI>

          

<DIV class = page-header>

<! --? Php echo $ item ---> news_title;?>

</DIV>

  

<DIV class = content>

<! --? Php echo $ item ---> news_intro;?>

</DIV>

  

</LI>

<! --? Php endforeach ;? -->

</UL>

  

<DIV class = pagination>

<! --? Php

$ This ---> widget ('clinkpager', array (

'Pages '=> $ pages,

'Selectedpagecssclass '=> 'active', // class on the current page

'Hidenpagecssclass '=> 'disabled', // class of the disabled page

'Header' => '', // the content displayed before the page

'Maxbuttoncount' => 10, // display the number of pages

'Htmlopexception' => array ('class' => ''),

'Firstpagelabel '=> 'homepage ',

'Nextpagelabel '=> 'next page ',

'Prevpagelabel '=> 'previous page ',

'Lastpagelabel '=> 'Last page ',

            ) 

);

?>

</DIV>


3. Implement paging for DAO.

The code is as follows: Copy code

[Controller layer]

Public function actionReport ()
{
$ SQL = "select remitdate, sum (rate) sumrate from td_delivery
Group by remitdate
Order by remitdate desc ";
$ Criteria = new CDbCriteria ();
$ Result = Yii: app ()-> db-> createCommand ($ SQL)-> query ();
$ Pages = new CPagination ($ result-> rowCount );
$ Pages-> pageSize = 2;
$ Pages-> applyLimit ($ criteria );
$ Result = Yii: app ()-> db-> createCommand ($ SQL. "LIMIT: offset,: limit ");
$ Result-> bindValue (': offset', $ pages-> currentPage * $ pages-> pageSize );
$ Result-> bindValue (': limit', $ pages-> pageSize );
$ Posts = $ result-> query ();
$ This-> render ('report', array (
'Posts' => $ posts,
'Pages '=> $ pages,
));
}

[View layer]


<? Php foreach ($ posts as $ row):?>
<? Php echo CHtml: link ($ row ["remitdate"], array ('delivery/view', 'remitdate' => $ row ["sumrate"]);?>
<? Php echo $ row ["sumrate"]. "<br/>"?>
<? Php endforeach;?>
<? Php
// Pagination widget code:
$ This-> widget ('clinkpager', array ('page' => $ pages ));
?>


Advantage: high DAO efficiency; disadvantage: The view layer needs to write some styles by itself, which is a little more troublesome.

4. Implement paging for widgets

The code is as follows: Copy code

[Model layer]

/**
* @ Var string attribute: Daily freight (used for statistics)
* You need to declare the newly added fields.
*/
Public $ dayrate;


/*
* Statistical function: collects daily freight charges.
*/
Public function statistics ()
{
$ Criteria = new CDbCriteria;
$ Criteria-> select = 'remitdate, sum (rate) AS dayrate ';
$ Criteria-> group = 'remitdate ';

Return new CActiveDataProvider (get_class ($ this), array (
'Criteria '=> $ criteria,
'Sort '=> array (
// Set the field for clicking to sort in the header
'Bubuckets' => array (
'Remitdate ',
'Dayrate' => array (
'Asc '=> 'dayrate ',
'Desc' => 'dayrate desc ',
)
),
'Defaultorder' => 'remitdate desc ',
),
));
}

[Controller layer]


/**
* Waybill statistics:
* Statistics by date
*/
Public function actionReport ()
{
$ Model = new Delivery ('Statistics ');
$ Model-> unsetAttributes (); // clear any default values
 
$ This-> render ('report', array (
'Model' => $ model,
));
}

[View layer]


<? Php $ this-> widget ('zii. widgets. grid. CGridView ', array (
'Id' => 'Delivery-grid ',
'Dataprovider' => $ model-> statistics (),
'Filter' => $ model,
'Columns '=> array (
'Remitdate ',
'Dayrate ',
Array (
'Class' => 'cbuttoncolumn ',
),
),
);?>

Advantage: you can use the built-in style. Disadvantage: the efficiency is slightly lower.

5. Ajax paging

In YII, there are multiple implementation methods for ajax paging. The traditional method is to write JS in view for implementation, which is probably like this:

In view, the general logic of js is as follows:

The code is as follows: Copy code

$ ('# Listview. yiiPager a'). live ('click', function (){
$. Ajax ({
Url: $ (this). attr ('href '),
Success: function (html ){
('{Listview'{.html (html );
            }
});
Return false; // block the tag
});

Then, judge the ajax request in the controller, and then use the renderPartial method to render the partial List view. Then, the partial view will be

Method to fill in the div with partial refresh. The approximate logic of controller is

The code is as follows: Copy code

If (Yii: app ()-> request-> isAjaxRequest ){
$ This-> renderPartial ('_ comments', array (
'Model' => $ model,
'Comments' => $ comments, // in the partial view, foreach obtains each data entry.
'Pages '=> $ pages,
));
Yii: app ()-> end ();
}

Later, it was found that CListview in YII is more convenient and encapsulated by Pages. foreach displays the list and supports data sorting. For more information, see the yii api manual.

Mining. CListview is the default ajax paging method. The usage is as follows:

The code is as follows: Copy code

Controller:

$ Criteria = new CDbCriteria ();
$ Criteria-> order = ''create _ time 'desc ';

$ DataProvider = new CActiveDataProvider ('comments', array (
'Pagination' => array (
'Pagesize' => Yii: app ()-> params ['commentsperpage'], // set the number of entries to determine the number of retrieved data entries
),
'Criteria '=> $ criteria,
));
$ This-> render ('comments', array (
'Model' => $ model,
'Dataprovider' => $ dataProvider,
));

Then in the view:

The code is as follows: Copy code

<? Php $ this-> widget ('zii. widgets. Clistview', array (
'Dataprovider' => $ dataProvider,
'Itemview' => '_ comments ',
// 'Ajaxupdate' => false, // this will not result in AJAX paging
'Pager' => array (// pager configuration information. The default value is <CODE> array ('class' => 'clinkpager') </CODE>.
'Nextpagelabel '=> 'next page & raquo ;',
'Prevpagelabel '=>' & laquo;'
),
// You can also configure some sorting rules here. For details, refer to the manual.
);?>

In this way, Ajax paging is implemented, which is very convenient.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.