0

I want to add toolbar in my custom collection which are comes from database , How to call toolbar in my custom Module any one have an idea in magento2. I want to show toolbar as same like display in product list page.

I want this type of toolbar in my custom collection of module: enter image description here

1
  • i want to show same like list page of product collection. Commented Jun 30, 2020 at 10:30

1 Answer 1

3

You can use below code to show All Product With the toolbar

Step- 1 create a custom module

create file app\code\Rasik\AllProduct\registration.php

<?php
/**
* Copyright © 2015 Magento. All rights reserved.
* See COPYING.txt for license details.
*/
\Magento\Framework\Component\ComponentRegistrar::register(
\Magento\Framework\Component\ComponentRegistrar::MODULE,
'Rasik_AllProduct',
__DIR__
);

Step-2 create the module.xml

app\code\Rasik\AllProduct\etc\module.xml

<?xml version="1.0"?>

<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:Module/etc/module.xsd">
    <module name="Rasik_AllProduct" setup_version="1.0.5">
        <sequence>
            <module name="Rasik_AllProduct"/>
        </sequence>
    </module>
</config>

Step-3 create the routes.xml

app\code\Rasik\AllProduct\etc\frontend\routes.xml

<?xml version="1.0"?>
<!--
/**
 * Copyright © Magento, Inc. All rights reserved.
 * See COPYING.txt for license details.
 */
-->
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="allproduct" frontName="allproduct">
            <module name="Rasik_AllProduct" />
        </route>
    </router>
</config>

Step -4 Create Block app\code\Rasik\AllProduct\Block\Index.php

<?php
namespace Rasik\AllProduct\Block;

Class Index extends \Magento\Framework\View\Element\Template
{    
    
    protected $_productCollectionFactory;
    protected $helperFactory;
    protected $listProductBlock;
    private $request;
    protected $_categoryFactory;
    protected $_attributeFactory;
    protected $_productListHelper;
        
    public function __construct(
        \Magento\Backend\Block\Template\Context $context,        
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,  
        \Magento\Catalog\Helper\ImageFactory $helperFactory,
        \Magento\Catalog\Block\Product\ListProduct $listProductBlock,
        \Magento\Framework\App\Request\Http $request,
        \Magento\Catalog\Model\CategoryFactory $categoryFactory,
        \Magento\Catalog\Model\ResourceModel\Eav\Attribute $attributeFactory,
        array $data = []
    )
    {    
        $this->_attributeFactory = $attributeFactory;
        $this->_categoryFactory = $categoryFactory;
        $this->_productCollectionFactory = $productCollectionFactory;
        $this->helperFactory = $helperFactory;
        $this->listProductBlock = $listProductBlock;
        $this->request =$request;
        parent::__construct($context, $data);
    }
    
    public function getProductCollection()
    {

        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $filterableAttributes = $objectManager->create(\Magento\Catalog\Model\Layer\Category\FilterableAttributeList::class);
        $attributes = $filterableAttributes->getList();

        $price=$this->getRequest()->getParam('price');
        $cat=$this->getRequest()->getParam('cat');
        $sortby=$this->getRequest()->getParam('product_list_order');
        if (empty($sortby)) {
           $sortby='position';
        }
        $listdesc=$this->getRequest()->getParam('product_list_dir');
        
        $page=($this->getRequest()->getParam('p'))? $this->getRequest()->getParam('p') : 1;
           //get values of current limit
        $pageSize=($this->getRequest()->getParam('limit'))? $this->getRequest()->getParam('limit') : 3;
        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToSelect('*');
        $collection->setOrder('title','ASC');
        $collection->setPageSize($pageSize);
        $collection->setCurPage($page);
           
        foreach ($attributes as $attributes1 ) {
                     $attributefrontend = $attributes1->getFrontendInput();
                   if (!empty($_REQUEST[$attributes1->getAttributeCode()]) && $attributefrontend=="select") {
                        $collection->addAttributeToFilter($attributes1->getAttributeCode(), $_REQUEST[$attributes1->getAttributeCode()]);
                    }
                   if (!empty($_REQUEST[$attributes1->getAttributeCode()]) && $attributefrontend=="multiselect") {
                     $collection->addAttributeToFilter($attributes1->getAttributeCode(), array('in' => array((int)$_REQUEST[$attributes1->getAttributeCode()])));
                   }
                    
                    if (isset($price) || isset($cat) || isset($_REQUEST[$attributes1->getAttributeCode()]) || isset($sortby)) {

                         $pricebetween=explode("-",$price);        
                     
                       if (!empty($pricebetween[0])) {
                         $collection->addAttributeToFilter('price', array('gteq' => $pricebetween[0]));
                       }
                       if (!empty($pricebetween[1])) { 
                           $collection->addAttributeToFilter('price', array('lteq' => $pricebetween[1]));
                       }
                       if (!empty($cat)) {
                           $category = $this->_categoryFactory->create()->load($cat);
                           $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);
                       }
         
                          
                    }
                    if ($sortby=='position') {
                            $collection->setOrder($sortby,'ASC');
                       }
                       if (!empty($listdesc)) {
                           $collection->setOrder($sortby,'DESC');
                       } else {
                           $collection->setOrder($sortby,'ASC');
                       }
             
        }
        /*echo $collection->getSelect(); */

        return $collection;
    }

    public function getImage($product)
    {
     // for image url get
      return  $this->helperFactory->create()->init($product, 'product_thumbnail_image')->resize(150)->getUrl();       
    }
    protected function _prepareLayout()
    {
        parent::_prepareLayout();
        $this->pageConfig->getTitle()->set(__('products'));
        if ($this->getProductCollection()) {
        $toolbar = $this->getLayout()
                   ->createBlock(
                'Magento\Catalog\Block\Product\ProductList\Toolbar',
                'product_list_toolbar'
                )
                ->setTemplate('Rasik_AllProduct::product/list/toolbar.phtml')
                ->setCollection($this->getProductCollection());

            $pager = $this->getLayout()->createBlock(
                'Magento\Theme\Block\Html\Pager',
                'AllProduct.product.pager'
            )->setAvailableLimit(array(3=>3,6=>6,9=>9))->setShowPerPage(true)->setCollection(
                $this->getProductCollection()
            );
            $this->setChild('pager', $pager);
            $this->setChild('toolbar', $toolbar);
            $this->getProductCollection()->load();
        }
        return $this;
    }
    public function getPagerHtml()
    {
        return $this->getChildHtml('pager');
    }
    public function getToolbarHtml()
    {
        return $this->getChildHtml('toolbar');
    }
    public function getMode()
    {
        return $this->getChildBlock('toolbar')->getCurrentMode();
    }
     
}

Step -5 create template file app\code\Rasik\AllProduct\view\frontend\templates\Product\list\toolbar.phtml

<?php
/**
 * Product list toolbar
 *
 * @var $block \Magento\Catalog\Block\Product\ProductList\Toolbar
 */
use Magento\Catalog\Model\Product\ProductList\Toolbar;
?>
<?php if ($block->getCollection()->getSize()): ?>
    <div class="toolbar toolbar-products" data-mage-init='<?= /* @escapeNotVerified */ $block->getWidgetOptionsJson() ?>'>
        <?php if ($block->isExpanded()): ?>
            <?php include ($block->getTemplateFile('Magento_Catalog::product/list/toolbar/viewmode.phtml')) ?>
        <?php endif; ?>

        <?php include ($block->getTemplateFile('Magento_Catalog::product/list/toolbar/amount.phtml')) ?>

       <!-- //remove the pager section -->
        <!-- <?= $block->getPagerHtml() ?>

        <?php include ($block->getTemplateFile('Magento_Catalog::product/list/toolbar/limiter.phtml')) ?> -->

        <?php if ($block->isExpanded()): ?>
            <?php include ($block->getTemplateFile('Magento_Catalog::product/list/toolbar/sorter.phtml')) ?>
        <?php endif; ?>
    </div>
<?php endif ?>

Step -6 create the all product listing template app\code\Rasik\AllProduct\view\frontend\templates\index.phtml

<?php
 if ($block->getMode() == 'grid') {
        $viewMode = 'grid';
        $templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::SHORT_VIEW;
    } else {
        $viewMode = 'list';
        $templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::FULL_VIEW;
    }
 ?>
<?= $block->getToolbarHtml() ?>
<div class="products wrapper <?= /* @escapeNotVerified */ $viewMode ?> products-<?= /* @escapeNotVerified */ $viewMode ?>">
    <ol class="products list items product-items">
        <?php
        const PARAM_NAME_BASE64_URL = 'r64';
        const PARAM_NAME_URL_ENCODED = 'uenc';
        use Magento\Framework\App\Action\Action;
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $priceHelper = $objectManager->create('Magento\Framework\Pricing\Helper\Data');
        $productCollection = $block->getProductCollection();
        foreach ($productCollection as $product) {
             $postParams = $block->getAddToCartPostParams($product);
            ?>
            <li class="item product product-item">                
                <div class="product-item-info" data-container="product-grid">
                <a href="<?= $product->getProductUrl(); ?>" class="product photo product-item-photo" tabindex="-1">

                    <span class="product-image-container" style="width:240px;">
                        <span class="product-image-wrapper" style="padding-bottom: 125%;">
                            <img class="product-image-photo" src="<?= $this->getImage($product); ?>" width="240" height="300" alt="t-shirt Man">
                            <!-- <img class="product-image-photo" src="<?= $this->getUrl().'pub/media/catalog/product'.$product->getImage(); ?>" width="240" height="300" alt="t-shirt Man"> -->
                        </span>
                        </span>
                    </a>
                    <div class="product details product-item-details">
                        <strong class="product name product-item-name">
                            <a class="product-item-link" href="<?php echo  $product->getProductUrl(); ?>">
                                <?php echo $product->getName()."</br>";?> 
                                <?php echo "<b>"."SKU"."</b>"." :".$product->getSku();?> 
                            </a>
                        </strong>
                        <div class="price-box price-final_price" data-role="priceBox" data-product-id="2">


                            <span class="price-container price-final_price tax weee">
                                <span id="product-price-2" data-price-amount="20" data-price-type="finalPrice" class="price-wrapper ">
                                    <span class="price"><?php echo $priceHelper->currency($product->getFinalPrice(), true, false); ?></span>    </span>
                                </span>

                            </div>                        
                            <div class="product-item-inner">
                                <div class="product actions product-item-actions">
                                    <div class="actions-primary">
                                        <form data-role="tocart-form" id="addform" action="<?php /* @escapeNotVerified */ echo $postParams['action']; ?>" method="post">
                                            <input type="hidden" name="product" value="<?php /* @escapeNotVerified */ echo $postParams['data']['product']; ?>">
                                            <input type="hidden" name="<?php /* @escapeNotVerified */ echo Action::PARAM_NAME_URL_ENCODED; ?>" value="<?php /* @escapeNotVerified */ echo $postParams['data'][Action::PARAM_NAME_URL_ENCODED]; ?>">
                                            <?php echo $block->getBlockHtml('formkey')?>
                                            <?php $storeManager = \Magento\Framework\App\ObjectManager::getInstance()->get('Magento\Store\Model\StoreManagerInterface'); ?>
                                            <button type="submit"
                                            title="<?php echo $block->escapeHtml(__('Add to Cart')); ?>"class="action tocart primary">
                                            <span><?php /* @escapeNotVerified */ echo __('Add to Cart') ?></span>
                                        </button>
                                    </form> 
                                    </div>
                                    <div data-role="add-to-links" class="actions-secondary">
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                     <?php } ?>
                </li>  
        </ol>
        </div>
        <?php if ($block->getPagerHtml()): ?>
    <div class="order-products-toolbar toolbar bottom"><?php echo $block->getPagerHtml(); ?></div>
<?php endif ?>

step -7 create the layout file app\code\Rasik\AllProduct\view\frontend\layout\allproduct_index_index.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="2columns-left" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <head>
        <css src="Magento_Swatches::css/swatches.css" />
    </head>
    <attribute name="class" value="page-with-filter"/>
        <referenceContainer name="content">
            <block class="Rasik\AllProduct\Block\Index" name="allproduct_index_index" template="Rasik_AllProduct::index.phtml" />
        </referenceContainer>
</page>

step -8 create the layout file app\code\Rasik\AllProduct\view\frontend\layout\default.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" layout="1column" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
    <body>
        <referenceBlock name="product_list_toolbar_pager" remove="true" />
    </body>
</page>

I hope this is helpful to you!!

7
  • Thank you for your answer. but I want toolbar in my custom table not from product collection how can I do that can you please suggest me @Rasik Niyani Commented Jul 2, 2020 at 5:05
  • Please change the collection based on the requirement. You need to just change getProductCollection. Commented Jul 2, 2020 at 5:10
  • I have alread did it but nothing working Commented Jul 2, 2020 at 5:13
  • toolbar load successfully on the frontend? Commented Jul 2, 2020 at 5:15
  • no nothing showing in fronend just only page title shows Commented Jul 2, 2020 at 5:17

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