Magento 2: How to get sub category and their products in collection?How to get the categories of the product collection loadedFilter Category Collection by Enabled, Visible ProductsProducts from a category plus any children and get category ID for conditions from collectionGet sub category of current category in magento2Magento 2 get category count getChildCategories()Add category IDs to product collectionHow to filter product collection using 2 or more category filters in magento2?Magento 2 : No products displaying on sub category pagesMagento 2. How to get All Parent Categories Ids from current category IDHow to make a navigation side bar with category and sub category Magento 2

I hit a pipe with a mower and now it won't turn

Who voices the character "Finger" in The Fifth Element?

How do we separate rules of logic from non-logical constraints?

Variable dimensional integrals

I need help with pasta

My colleague is constantly blaming me for his errors

The warming up game

Bin Packing with Relational Penalization

Is Cyclic Ether oxidised by periodic acid

Comment traduire « That screams X »

Reusable spacecraft: why still have fairings detach, instead of open/close?

Why was Mal so quick to drop Bester in favour of Kaylee?

What kind of jet plane is this?

Most elegant way to write a one-shot 'if'

How to describe POV characters?

Could human civilization live 150 years in a nuclear-powered aircraft carrier colony without resorting to mass killing/ cannibalism?

How did Lefschetz do mathematics without hands?

Are gliders susceptible to bird strikes?

Different budgets within roommate group

If two black hole event horizons overlap (touch) can they ever separate again?

Why is Japan trying to have a better relationship with Iran?

Will writing actual numbers instead of writing them with letters affect readership?

Can a stressful Wish's Strength reduction be cured early by a Greater Restoration spell?

Sharing referee/AE report online to point out a grievous error in refereeing



Magento 2: How to get sub category and their products in collection?


How to get the categories of the product collection loadedFilter Category Collection by Enabled, Visible ProductsProducts from a category plus any children and get category ID for conditions from collectionGet sub category of current category in magento2Magento 2 get category count getChildCategories()Add category IDs to product collectionHow to filter product collection using 2 or more category filters in magento2?Magento 2 : No products displaying on sub category pagesMagento 2. How to get All Parent Categories Ids from current category IDHow to make a navigation side bar with category and sub category Magento 2






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty margin-bottom:0;








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.










share|improve this question






















  • 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
    Jun 20 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

    – Nitin Pawar
    Jun 20 at 8:49

















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.










share|improve this question






















  • 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
    Jun 20 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

    – Nitin Pawar
    Jun 20 at 8:49













0












0








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.










share|improve this question














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.







magento2 collection






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Jun 20 at 8:22









Nitin PawarNitin Pawar

7971 gold badge16 silver badges40 bronze badges




7971 gold badge16 silver badges40 bronze badges












  • 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
    Jun 20 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

    – Nitin Pawar
    Jun 20 at 8:49

















  • 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
    Jun 20 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

    – Nitin Pawar
    Jun 20 at 8:49
















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
Jun 20 at 8:42





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
Jun 20 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

– Nitin Pawar
Jun 20 at 8:49





@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

– Nitin Pawar
Jun 20 at 8:49










1 Answer
1






active

oldest

votes


















1














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



protected $categorycollectionFactory;
public function __construct(MagecompBlogModelResourceModelCategoryCollectionFactory $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', MagentoCatalogModelProductVisibility::VISIBILITY_BOTH);
$collection->addAttributeToFilter('status',MagentoCatalogModelProductAttributeSourceStatus::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(
    'MagentoThemeBlockHtmlPager',
    '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 ?>







share|improve this answer

























    Your Answer








    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "479"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );













    draft saved

    draft discarded


















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f278989%2fmagento-2-how-to-get-sub-category-and-their-products-in-collection%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    1 Answer
    1






    active

    oldest

    votes








    1 Answer
    1






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    1














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



    protected $categorycollectionFactory;
    public function __construct(MagecompBlogModelResourceModelCategoryCollectionFactory $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', MagentoCatalogModelProductVisibility::VISIBILITY_BOTH);
    $collection->addAttributeToFilter('status',MagentoCatalogModelProductAttributeSourceStatus::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(
      'MagentoThemeBlockHtmlPager',
      '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 ?>







    share|improve this answer



























      1














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



      protected $categorycollectionFactory;
      public function __construct(MagecompBlogModelResourceModelCategoryCollectionFactory $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', MagentoCatalogModelProductVisibility::VISIBILITY_BOTH);
      $collection->addAttributeToFilter('status',MagentoCatalogModelProductAttributeSourceStatus::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(
        'MagentoThemeBlockHtmlPager',
        '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 ?>







      share|improve this answer

























        1












        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(MagecompBlogModelResourceModelCategoryCollectionFactory $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', MagentoCatalogModelProductVisibility::VISIBILITY_BOTH);
        $collection->addAttributeToFilter('status',MagentoCatalogModelProductAttributeSourceStatus::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(
          'MagentoThemeBlockHtmlPager',
          '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 ?>







        share|improve this answer













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



        protected $categorycollectionFactory;
        public function __construct(MagecompBlogModelResourceModelCategoryCollectionFactory $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', MagentoCatalogModelProductVisibility::VISIBILITY_BOTH);
        $collection->addAttributeToFilter('status',MagentoCatalogModelProductAttributeSourceStatus::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(
          'MagentoThemeBlockHtmlPager',
          '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 ?>








        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered Jun 20 at 8:56









        Anas MansuriAnas Mansuri

        56715 bronze badges




        56715 bronze badges



























            draft saved

            draft discarded
















































            Thanks for contributing an answer to Magento Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fmagento.stackexchange.com%2fquestions%2f278989%2fmagento-2-how-to-get-sub-category-and-their-products-in-collection%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Category:9 (number) SubcategoriesMedia in category "9 (number)"Navigation menuUpload mediaGND ID: 4485639-8Library of Congress authority ID: sh85091979ReasonatorScholiaStatistics

            Circuit construction for execution of conditional statements using least significant bitHow are two different registers being used as “control”?How exactly is the stated composite state of the two registers being produced using the $R_zz$ controlled rotations?Efficiently performing controlled rotations in HHLWould this quantum algorithm implementation work?How to prepare a superposed states of odd integers from $1$ to $sqrtN$?Why is this implementation of the order finding algorithm not working?Circuit construction for Hamiltonian simulationHow can I invert the least significant bit of a certain term of a superposed state?Implementing an oracleImplementing a controlled sum operation

            Magento 2 “No Payment Methods” in Admin New OrderHow to integrate Paypal Express Checkout with the Magento APIMagento 1.5 - Sales > Order > edit order and shipping methods disappearAuto Invoice Check/Money Order Payment methodAdd more simple payment methods?Shipping methods not showingWhat should I do to change payment methods if changing the configuration has no effects?1.9 - No Payment Methods showing upMy Payment Methods not Showing for downloadable/virtual product when checkout?Magento2 API to access internal payment methodHow to call an existing payment methods in the registration form?