Magento – Magento 2, how to add color swatches to custom widget template

color-swatchescustommagento2widgets

The custom module lists certain configurable products. I need to display the color swatches, I tried below but it returns nothing!

in myTempalte.phtml

  <?php

    use Magento\Framework\App\Action\Action;

    // @codingStandardsIgnoreFile

    $templateType = \Magento\Catalog\Block\Product\ReviewRendererInterface::SHORT_VIEW;

    /**
     * Position for actions regarding image size changing in vde if needed
     */
    $pos = $block->getPositioned();
    /**
     * Product list template
     *
     * @var $block \Magento\Catalog\Block\Product\ListProduct
     */
    $_productCollection = $this->createCollection();

    $blockVariant = $this->getLayout()
        ->createBlock('Magento\Swatches\Block\Product\Renderer\Listing\Configurable')
        ->setTemplate('Magento_Swatches::product/listing/renderer.phtml');

..... // in loop I have below for color div

       <?php if ($_product->getTypeId() == "configurable" ):?>
                            <div class="product-available-variant">
                                <?php $blockVariant->getProductDetailsHtml($_product); ?>
                            </div>
                        <?php endif?> // and rest of the loop

How to add color swatches block to widget template, below does not work:

$blockVariant = $this->getLayout()
        ->createBlock('Magento\Swatches\Block\Product\Renderer\Listing\Configurable')
        ->setTemplate('Magento_Swatches::product/listing/renderer.phtml');

Best Answer

Answering here with reference to https://magento.stackexchange.com/a/223599/45214 .

In app/design/frontend/MyCompany/mytheme/Magento_Catalog/templates/product/list/items.phtml please add below code :

<?php if($_item->getTypeId() == \Magento\ConfigurableProduct\Model\Product\Type\Configurable::TYPE_CODE){

 $swatchBlock = $this->getLayout()->createBlock("Magento\Swatches\Block\Product\Renderer\Listing\Configurable")->setTemplate("Magento_Swatches::product/listing/renderer.phtml");
   echo $swatchBlock->setProduct($_item)->toHtml();                           
} ?>

And also in

app/design/frontend/MyCompany/mytheme/Magento_Swatches/layout/catalog_product_view.xml

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

</page>
Related Topic