Code example for yii2 to implement the "previous, next" function

Source: Internet
Author: User
You need to add the previous article and the next button on many pages. the editor thinks it is quite good. now I will share it with you and give you a reference. Let's take a look at the details page of a short answer article. you need to add the previous article and the next button at the bottom of the page to analyze the following, the title and id of the article (as a parameter) are the most basic requirements ).

The first thought is to add or subtract 1 from the current id, but considering that if some IDs are lost, the following code is available to query records larger and smaller than the current id and limit them to one.

The code is as follows. For more information, see.

Controller

// Query the previous article $ prev_article = your model: find ()-> andFilterWhere (['<', 'id', $ id]) -> andFilterWhere ([other conditions)-> orderBy (['id' => SORT_DESC])-> limit (1)-> one (); // query the next-Article $ next_article = your model: find ()-> andFilterWhere (['>', 'id', $ id]) -> andFilterWhere (other conditions)-> orderBy (['id' => SORT_ASC])-> limit (1)-> one (); $ model ['prev _ article'] = ['URL' =>! Is_null ($ prev_article )? Url: current (['id' => $ prev_article-> id]): 'javascript:; ', 'title' =>! Is_null ($ prev_article )? $ Prev_article-> title: 'No Longer',]; $ model ['next _ article'] = ['URL' =>! Is_null ($ next_article )? Url: current (['id' = >$ next_article-> id]): 'javascript:; ', 'title' =>! Is_null ($ next_article )? $ Next_article-> title: 'No Longer',]; return $ this-> render ('View', 'model' => $ model ,);

View

Previous article: ">

Next Article: ">

The above is all the content of this article. I hope it will help you learn and support PHP.

For more articles on code instances for yii2 implementation of the "previous, next" function, please follow PHP Chinese network!

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.