Skip to main content

This site requires you to update your browser. Your browsing experience maybe affected by not having the most up to date version.

General Questions /

General questions about getting started with SilverStripe that don't fit in any of the categories above.

Moderators: martimiz, Sean, biapar, Willr, Ingo, swaiba

Re: Archive Pagination - Is it possible to use the page number rather than starting point


Go to End
Reply


762 Views

Avatar
MarijnKampf

Community Member, 175 Posts

4 June 2010 at 8:58pm

I've made a small improvement to the code paginating using page numbers found in the archived post at http://silverstripe.org/archive/show/219742

The pagination created multiple URLs for the first page which is a SEO no-no. Fixed the URLs so the page URL variable isn't included when referring to the first page of the results.

Quick note, I seem to remember a changelog note that $_SERVER['REQUEST_URI'] should no longer be used in 2.4, I tried to search for the correct function but I couldn't find it. It could be that I'm confused with something else.

PaginatedByPage.php

class PaginatedByPage extends Extension {

   protected $pageNumGetVar = "page";

   // I couldn't find a HTTP::removeGetVar function so came up with this
   function noGetVar() {
   	 $url = preg_replace("/[&?]" . $this->pageNumGetVar . "=[0-9]*/", "", $_SERVER['REQUEST_URI']);
   	 return $url;
   }

   public function PageNums($maxPages = 0){
      $ret = new DataObjectSet();
      if($maxPages) {
         $startPage = ($this->owner->CurrentPage() - floor($maxPages / 2)) - 1;
         $endPage = $this->owner->CurrentPage() + floor($maxPages / 2);

         if($startPage < 0) {
            $startPage = 0;
            $endPage = $maxPages;
         }
         if($endPage > $this->owner->TotalPages()) {
            $endPage = $this->owner->TotalPages();
            $startPage = max(0, $endPage - $maxPages);
         }

      } else {
         $startPage = 0;
         $endPage = $this->owner->TotalPages();
      }

      for($i=$startPage; $i < $endPage; $i++){
         if($i == 0) {
           $link = $this->noGetVar();
         } else {
            $link = HTTP::setGetVar($this->pageNumGetVar, $i + 1);
         }
         $thePage = new ArrayData(array(
               "PageNum" => $i+1,
               "Link" => $link,
               "CurrentBool" => ($this->owner->CurrentPage() == $i+1)?true:false,
               )
         );
         $ret->push($thePage);
      }
      return $ret;
   }

   public function PageNextLink() {
      return HTTP::setGetVar($this->pageNumGetVar, $this->owner->CurrentPage() + 1);
   }

   public function PagePrevLink() {
   	 if ($this->owner->CurrentPage() > 2) {
   	 Debug::Show($this->owner->CurrentPage());
       return HTTP::setGetVar($this->pageNumGetVar, $this->owner->CurrentPage() - 1);
     } else return $this->noGetVar();
   }
}