Yii paging usage example _ php instance

Source: Internet
Author: User
Tags api manual php foreach
This article mainly introduces the Yii paging usage, and analyzes several common paging methods and their application features in detail in the form of instances, which is of great practical value, for more information about Yii paging methods and instance code, see below. common paging and ajax implementation paging are provided here. I hope this article will be helpful to you.

First: CListView paging for object-based data paging

Controller:

The code is as follows:

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:

The code is as follows:

<? 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' =>'

No data!

', // 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 ',
),
));
?>

Type 2: CLinkPager for array-based data paging

Controller:

The code is as follows:

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:

The code is as follows:


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



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



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



  • <? Php endforeach;?>



<? 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 ',
)
);
?>

Third: implement paging for DAO.

Controller layer:

The code is as follows:

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:

The code is as follows:

<? Php foreach ($ posts as $ row):?>
<? Php echo CHtml: link ($ row ["remitdate"], array ('delivery/view', 'remitdate' => $ row ["sumrate"]);?>
<? Php echo $ row ["sumrate"]."
"?>
<? 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.

Fourth: implement paging for widgets

Model layer:

The code is as follows:

/**
* @ 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:

The code is as follows:

/**
* 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:

The code is as follows:

<? 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.

Type 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:

$ ('# 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 is filled into the partially refreshed p by the ajax method in the view. The approximate logic of controller is:

The code is as follows:

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. Specific information can be found in the yii api manual. CListview is the default ajax paging method. the usage is as follows:

Controller:

The code is as follows:

$ 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:

<? 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. Default value:array('class'=>'CLinkPager'). You can also configure it yourself.
'Nextpagelabel '=> 'next page »',
'Prevpagelabel '=>' «Previous Page'
),
// 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.

I hope this article will help you design PHP programs based on the Yii Framework.

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.