0

I want to get the categories and related products in collection using parent category ID. So that i can show the grid like

sub category 1

sub category 1's product 1
sub category 1's product 2
sub category 1's product 3

sub category 2

sub category 2's product 1
sub category 2's product 2
sub category 2's product 3 

and so on. I can get the products in foreach but I need to add pagination also.

2
  • I think for that first you'll need to get all the sub categories after that you'll get all the products of the specific categories.
    – Asad Khan
    Commented Jun 20, 2019 at 8:42
  • @AsadKhan I want to print as it is given in the question. And I need to add the pagination if list is big, that's why I am searching for collection Commented Jun 20, 2019 at 8:49

1 Answer 1

1

Step by step guide to add pagination in custom collection of Magento 2: 1 Create Collection for Pager:

protected $categorycollectionFactory;
    public function __construct(\Magecomp\Blog\Model\ResourceModel\Category\CollectionFactory $categorycollectionFactory) 
    { 
        $this->categorycollectionFactory = $categorycollectionFactory; 
    }
    public function getCategorydata()
    {
        $categoryId = 'yourcategoryid';
        $category = $this->_categoryFactory->create()->load($categoryId);
        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        $collection->addCategoryFilter($category);
        $collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
        $collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
        return $collection;
    }
  1. Add Collection to Pager and Set Available Limits.

    protected function _prepareLayout() { parent::_prepareLayout(); $this->pageConfig->getTitle()->set(__('Categories')); if ($this->getNews()) { $pager = $this->getLayout()->createBlock( 'Magento\Theme\Block\Html\Pager', 'magecomp.category.pager' )->setAvailableLimit(array(5=>5,10=>10,15=>15))->setShowPerPage(true)->setCollection( $this->getCategorydata() ); $this->setChild('pager', $pager); $this->getCategorydata()->load(); } return $this; }

  2. Getting the Child Block of the Pager

    public function getPagerHtml() { return $this->getChildHtml('pager'); }

  3. Add the following Code in phtml File to Call the Pager:

    <?php if ($block->getPagerHtml()): ?> <div class="order-products-toolbar toolbar bottom"><?php echo $block->getPagerHtml(); ?></div> <?php endif ?>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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