0

In magento pagination,

When I pass current page and per page, its showing accurate result but when I pass per page value and current page value if there is no record for current page its again showing previous record as was on previous page, means its not considering total number of records.

If there is only one record and I pass page no 2, its showing last page record instead of empty row because there only one record.

Find below code:

public function getProductDetailAction()
        {

          $error = "false";
          $categoryid = $this->getRequest()->getParam('category_id');
          $customer_id = $this->getRequest()->getParam('customer_id');
          $per_page = $this->getRequest()->getParam('per_page');
          $current_page = $this->getRequest()->getParam('current_page');
          if( !$categoryid || empty($categoryid)){
              $error = 'true';
              $response['msg'] = "Category id is required.";
          }
          if( !$customer_id || empty($customer_id)){
              $error = 'true';
              $response['msg'] = "Customer id is required.";
          }
          $category = new Mage_Catalog_Model_Category();
          $category->load($categoryid);
          $collection = $category->getProductCollection()
          ->setPageSize($per_page)
          ->setCurPage($current_page);
          $collection->addAttributeToSelect('*');
          foreach ($collection as $_product) {
              $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct( $_product->getId())->getData();
              // echo $stock["qty"];die;
              $product_data["id"] =  $_product->getId();
              $product_data["sku"] =  $_product->getSku();
              $product_data["name"] = $_product->getName();
              $product_data["type"] =  $_product->getTypeId();       
              $product_data["image"]  = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB).'media/catalog/product'.$_product->getImage();
              $product_data["url"] =  $_product->getProductUrl();
              $product_data["visibility"] =  $_product->isVisibleInSiteVisibility(); //getVisibility(); 
              $product_data["weight"] =  $_product->getWeight();
              $product_data["stock"] =  $stock["qty"] ? $stock["qty"] : '';
              $product_data["status"] =  $_product->getStatus();
              $product_data["wishlist"] =  'no';

              /*Start Get rating of each product by product id. */
              $reviews = Mage::getModel('review/review')
                ->getResourceCollection()
                ->addStoreFilter(Mage::app()->getStore()->getId())
                ->addEntityFilter('product', $_product->getId())
                ->addStatusFilter(Mage_Review_Model_Review::STATUS_APPROVED)
                ->setDateOrder()
                ->addRateVotes();
                  $avg = 0;
                  $ratings = array();
                  if (count($reviews) > 0) {
                      foreach ($reviews->getItems() as $review) {
                          foreach( $review->getRatingVotes() as $vote ) {
                              $ratings[] = $vote->getPercent();
                          }
                      }
                      $avg = array_sum($ratings)/count($ratings);
                  }

              $product_data["rating"] =  round($avg);


              $wishlist = $this->getWishListByCustomerId( $customer_id );

                foreach ($wishlist as $key => $value) {

                  if ( $value['product_id'] == $product_data["id"] ){

                      $product_data["wishlist"] =  'yes';

                  }
                }

              $product_data["category"] =  $_product->getCategoryIds(); 
              $product_data["weight"] = number_format((float)$_product->getWeight(), 2, '.', '');
              $product_data["description"]['short'] =  $_product->getShortDescription();
              $product_data["description"]['full'] = $_product->getDescription();
              $product_data["price"]["regular"] = $_product->getPrice();
              $product_data["price"]["final"] = $_product->getFinalPrice();
              $response['data']['Products'][]= $product_data;

          }
  • Hie Gopal, can you please look into my code where i am wrong. why my code is showing record if there is no record for given page. if there is only one record and i passed page no 2, its showing first page record. – Khalil ur Rehman Jan 5 '17 at 7:41
  • if there is total 2 page and you type ?p=3 or greater then 2 it will shaw you last page means page 2 – Gopal Patel Jan 5 '17 at 8:31
1

Example:

Your data

per page: 12
page no: 2

In collection :

$category = new Mage_Catalog_Model_Category();
$category->load($categoryid);
$collection = $category->getProductCollection()
   ->setPageSize($per_page)
   ->setCurPage($current_page);

If Collection size is 10 for given category id (means only one page exist) then if your given page no is greater then total no of page exist then it will show last page from the page collection

$collection = $category->getProductCollection()
          ->setPageSize($per_page);
$last_page_no=$collection->getLastPageNumber();
if($last_page_no>=$current_page)
{
   //Your further code
}

find your code

public function getProductDetailAction()
{

  $error = "false";
  $categoryid = $this->getRequest()->getParam('category_id');
  $customer_id = $this->getRequest()->getParam('customer_id');
  $per_page = $this->getRequest()->getParam('per_page');
  $current_page = $this->getRequest()->getParam('current_page');
  if( !$categoryid || empty($categoryid)){
      $error = 'true';
      $response['msg'] = "Category id is required.";
  }
  if( !$customer_id || empty($customer_id)){
      $error = 'true';
      $response['msg'] = "Customer id is required.";
  }
  $category = new Mage_Catalog_Model_Category();
  $category->load($categoryid);
  $collection = $category->getProductCollection()
    ->setPageSize($per_page);
  $last_page_no=$collection->getLastPageNumber();
  if($last_page_no>=$current_page)
  {
      $collection->setCurPage($current_page);
      $collection->addAttributeToSelect('*');
      foreach ($collection as $_product) {
          $stock = Mage::getModel('cataloginventory/stock_item')->loadByProduct( $_product->getId())->getData();
          // echo $stock["qty"];die;
          $product_data["id"] =  $_product->getId();
          $product_data["sku"] =  $_product->getSku();
          $product_data["name"] = $_product->getName();
          $product_data["type"] =  $_product->getTypeId();       
          $product_data["image"]  = Mage::getBaseUrl(Mage_Core_Model_Store::URL_TYPE_WEB).'media/catalog/product'.$_product->getImage();
          $product_data["url"] =  $_product->getProductUrl();
          $product_data["visibility"] =  $_product->isVisibleInSiteVisibility(); //getVisibility(); 
          $product_data["weight"] =  $_product->getWeight();
          $product_data["stock"] =  $stock["qty"] ? $stock["qty"] : '';
          $product_data["status"] =  $_product->getStatus();
          $product_data["wishlist"] =  'no';

          /*Start Get rating of each product by product id. */
          $reviews = Mage::getModel('review/review')
            ->getResourceCollection()
            ->addStoreFilter(Mage::app()->getStore()->getId())
            ->addEntityFilter('product', $_product->getId())
            ->addStatusFilter(Mage_Review_Model_Review::STATUS_APPROVED)
            ->setDateOrder()
            ->addRateVotes();
              $avg = 0;
              $ratings = array();
              if (count($reviews) > 0) {
                  foreach ($reviews->getItems() as $review) {
                      foreach( $review->getRatingVotes() as $vote ) {
                          $ratings[] = $vote->getPercent();
                      }
                  }
                  $avg = array_sum($ratings)/count($ratings);
              }

          $product_data["rating"] =  round($avg);


          $wishlist = $this->getWishListByCustomerId( $customer_id );

            foreach ($wishlist as $key => $value) {

              if ( $value['product_id'] == $product_data["id"] ){

                  $product_data["wishlist"] =  'yes';

              }
            }

          $product_data["category"] =  $_product->getCategoryIds(); 
          $product_data["weight"] = number_format((float)$_product->getWeight(), 2, '.', '');
          $product_data["description"]['short'] =  $_product->getShortDescription();
          $product_data["description"]['full'] = $_product->getDescription();
          $product_data["price"]["regular"] = $_product->getPrice();
          $product_data["price"]["final"] = $_product->getFinalPrice();
          $response['data']['Products'][]= $product_data;

      }
  }
  • Thanks Gopal, is it possible that collection will empty if no more record for next page instead of showing last page records from collection? – Khalil ur Rehman Jan 5 '17 at 9:18
  • @KhalilurRehman find updated code. I am not aware of your further logic so you have to handel $response['data']['Products'][] properly – Gopal Patel Jan 5 '17 at 9:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.