Magento 2 Configurable Product – How to Display Swatches on Homepage

configurable-productmagento2swatches

I have two products sliders

(based on \Magento\Catalog\Block\Product\Widget\NewWidget) on my homepage.

I would like to add swatches to these product sliders.

The sliders are added in my homepage.xml layout as below:

<container name="items.wrapper.slider" after="full.width.white.bar" htmlTag="div"
           htmlClass="wrapper wrapper--large c-catalog__products--slider-wrapper">
    <block class="Silvan\TestExtension\Block\Product\Widget\NewWidget"
           template="Magento_Catalog::product/widget/new/content/new_grid.phtml" name="new.products">
        <block class="Magento\Swatches\Block\Product\Renderer\Listing\Configurable" as="new.products.swatches" template="Magento_Swatches::product/listing/renderer.phtml" />
    </block>
</container>

I've tried to add the swatches by adding the block with class Magento\Swatches\Block\Product\Renderer\Listing\Configurable but this doesn't work as expected.

Does anyone know how to achieve this in homepage?

Thanks.

Best Answer

Create simple module for display swatches in configurable product in homepage.

You have to follow below steps to get swatches on homepage product collection,

app/code/Test/Homeslider/registration.php

<?php
\Magento\Framework\Component\ComponentRegistrar::register(
    \Magento\Framework\Component\ComponentRegistrar::MODULE,
    'Test_Homeslider',
    __DIR__
);

app/code/Test/Homeslider/etc/module.xml

<?xml version="1.0"?>
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="../../../../../lib/internal/Magento/Framework/Module/etc/module.xsd">
    <module name="Test_Homeslider" setup_version="1.0.0" schema_version="1.0.0">
        <sequence>
            <module name="Magento_Catalog"/>
        </sequence>
    </module>
</config>

app/code/Test/Homeslider/view/frontend/templates/products.phtml

<?php
use Magento\Framework\App\Action\Action;

$productCollection = $this->getProductCollection();
$imageBlock =  $block->getLayout()->createBlock('Magento\Catalog\Block\Product\ListProduct');
$showCart = true;
$type = 'widget-new-grid';
$viewMode = 'grid'; 
$image = 'category_page_grid';
$pos = $block->getPositioned();
?>
<div class="title">
    <strong class="newproduct">New Product</strong>
</div>

<div class="products-grid">
    <div id="topseller-slider" class="products list items product-items owlslider" data-jcarousel="true">
        <ul class="product-items" id="topsellerowlslider">
            <?php $iterator = 1; ?>
            <?php foreach ($productCollection as $_product): ?>
            <?php $productImage = $imageBlock->getImage($_product, 'category_page_grid'); 
                if ($pos == null) {                                                        
                    $position = ' style="left:' . $productImage->getWidth() . 'px;'
                        . 'top:' . $productImage->getHeight() . 'px;"';
                }
                ?>
            <?php /* @escapeNotVerified */ echo($iterator++ == 1) ? '<li class="product-item"><div class="product-item-info">' : '</div></li><li class="product-item"><div class="product-item-info">' ?>
            <a href="<?php echo $_product->getProductUrl(); ?>"><?php echo $productImage->toHtml()  ?></a>
            <div class="product details product-item-details">
                <strong class="product name product-item-name">
                <a class="product-item-link"  href="<?php /* @escapeNotVerified */ echo $_product->getProductUrl() ?>">
                <?php /* @escapeNotVerified */ echo $_product->getName(); ?>
                </a>
                </strong>
                <?php if ($showCart): ?>
                <?php echo $this->getProductPricetoHtml($_product, $type); ?>
                <?php echo $block->getProductDetailsHtml($_product); ?>
                <div class="product-item-inner">
                    <div class="product actions product-item-actions">
                        <div class="actions-primary"<?php echo strpos($pos, $viewMode . '-primary') ? $position : ''; ?>>
                            <?php if ($_product->isSaleable()): ?>
                            <?php $postParams = $block->getAddToCartPostParams($_product); ?>
                            <form data-role="tocart-form" 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')?>
                                <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>
                            <?php else: ?>
                            <?php if ($_product->getIsSalable()): ?>
                            <div class="stock available"><span><?php /* @escapeNotVerified */ echo __('In stock') ?></span></div>
                            <?php else: ?>
                            <div class="stock unavailable"><span><?php /* @escapeNotVerified */ echo __('Out of stock') ?></span></div>
                            <?php endif; ?>
                            <?php endif; ?>
                        </div>

                        <div class="actions-secondary" data-role="add-to-links">
                            <?php if ($this->helper('Magento\Wishlist\Helper\Data')->isAllow()): ?>
                                <a href="#"
                                   data-post='<?php /* @escapeNotVerified */ echo $block->getAddToWishlistParams($_product); ?>'
                                   class="action towishlist" data-action="add-to-wishlist"
                                   title="<?php /* @escapeNotVerified */ echo __('Add to Wish List') ?>">
                                    <span><?php /* @escapeNotVerified */ echo __('Add to Wish List') ?></span>
                                </a>
                            <?php endif; ?>
                            <?php if ($block->getAddToCompareUrl()) ?>
                                <?php $compareHelper = $this->helper('Magento\Catalog\Helper\Product\Compare');?>
                                <a href="#" class="action tocompare"
                                   data-post='<?php /* @escapeNotVerified */ echo $compareHelper->getPostDataParams($_product);?>'
                                   title="<?php /* @escapeNotVerified */ echo __('Add to Compare') ?>">
                                    <span><?php /* @escapeNotVerified */ echo __('Add to Compare') ?></span>
                                </a>
                            <?php endif; ?>
                        </div>
                    </div>
                </div>
            </div>
            <?php echo($iterator == count($productCollection)+1) ? '</div></li>' : '' ?>
            <?php endforeach ?>
        </ul>
    </div>
</div>
</div>
<?php if (!$block->isRedirectToCartEnabled()) : ?>
<script type="text/x-magento-init">
    {
        "[data-role=tocart-form], .form.map.checkout": {
            "catalogAddToCart": {}
        }
    }
</script>
<?php endif; ?>

create xml file for display inside homepage, app/code/Test/Homeslider/view/frontend/layout/cms_index_index.xml

<?xml version="1.0"?>
<page xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:View/Layout/etc/page_configuration.xsd">
      <head>
           <css src="Magento_Swatches::css/swatches.css"/>
    </head> 
    <body>
        <referenceBlock name="homepage.swatchrenderer">
                <block class="Magento\Swatches\Block\Product\Renderer\Listing\Configurable" as="configurable" template="Magento_Swatches::product/listing/renderer.phtml" />
        </referenceBlock>     

        <referenceContainer name="main">
          <container name="topproduct" htmlTag="div" htmlClass="topproduct">
                  <block class="Test\Homeslider\Block\Productslist" name="productlist" template="Test_Homeslider::products.phtml">
                      <block class="Magento\Framework\View\Element\RendererList" name="homepage.swatchrenderer" as="homepage.toprenderers">
                        <block class="Magento\Framework\View\Element\Template" as="default"/>
                      </block>
                  </block>
           </container>
        </referenceContainer>
    </body>
</page>

Create Block file, app/code/Test/Homeslider/Block/Productslist.php

<?php
namespace Test\Homeslider\Block;
use Magento\Catalog\Block\Product\ListProduct;
use Magento\Catalog\Model\Category;
use Magento\Catalog\Model\Product;

class Productslist extends \Magento\Framework\View\Element\Template
{   
    protected $_productCollectionFactory;    

    public function __construct(      
        \Magento\Framework\View\Element\Template\Context $context,    
        \Magento\Catalog\Block\Product\Context $gridcontext,  
        \Magento\Catalog\Model\ResourceModel\Product\CollectionFactory $productCollectionFactory,       
        \Magento\Catalog\Block\Product\ListProduct $listProductBlock,

        array $data = []
    )
    {   
        $this->_productCollectionFactory = $productCollectionFactory; 
        $this->listProductBlock = $listProductBlock;
        $this->reviewRenderer = $gridcontext->getReviewRenderer();     
        $this->_compareProduct = $gridcontext->getCompareProduct();
        $this->_wishlistHelper = $gridcontext->getWishlistHelper();     
        parent::__construct($context, $data);
    }

    public function isRedirectToCartEnabled()
    {
        return $this->_scopeConfig->getValue(
            'checkout/cart/redirect_to_cart',
            \Magento\Store\Model\ScopeInterface::SCOPE_STORE
        );
    }

    public function getProductDetailsHtml(\Magento\Catalog\Model\Product $product)
    {
        $renderer = $this->getDetailsRenderer($product->getTypeId());
        if ($renderer) {
            $renderer->setProduct($product);
            return $renderer->toHtml();
        }
        return '';
    }

    public function getDetailsRenderer($type = null)
    {
        if ($type === null) {
            $type = 'default';
        }
        $rendererList = $this->getDetailsRendererList();
        if ($rendererList) {
            return $rendererList->getRenderer($type, 'default');
        }
        return null;
    }

    protected function getDetailsRendererList()
    {
        return $this->getDetailsRendererListName() ? $this->getLayout()->getBlock(
            $this->getDetailsRendererListName()
        ) : $this->getChildBlock(
            'homepage.toprenderers'
        );
    }
    public function getProductPricetoHtml(
        \Magento\Catalog\Model\Product $product,
        $priceType = null
    ) {
        $priceRender = $this->getLayout()->getBlock('product.price.render.default');
        $price = '';
        if ($priceRender) {
            $price = $priceRender->render(
                \Magento\Catalog\Pricing\Price\FinalPrice::PRICE_CODE,
                $product
            );
        }
        return $price;
    }
    public function getProductCollection()
    {        
        $collection = $this->_productCollectionFactory->create();
        $collection->addAttributeToFilter('type_id', 'configurable');
        $collection->addAttributeToFilter('visibility', \Magento\Catalog\Model\Product\Visibility::VISIBILITY_BOTH);
        $collection->addAttributeToFilter('status',\Magento\Catalog\Model\Product\Attribute\Source\Status::STATUS_ENABLED);
        $collection->setPageSize(10); 
        $collection->addAttributeToSelect('*');
        return $collection;
    }

    public function getAddToCartPostParams($product)
    {
        return $this->listProductBlock->getAddToCartPostParams($product);
    }

    public function getAddToWishlistParams($product)
    {
        return $this->_wishlistHelper->getAddParams($product);
    }
    public function getAddToCompareUrl()
    {
        return $this->_compareProduct->getAddUrl();
    }
}

Run command,

php bin/magento setup:upgrade
php bin/magento setup:static-content:deploy
Related Topic