1

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');

1 Answer 1

1

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>
1
  • it work perfect on Magento2.3 but on Magento 2.4 it give error Error: Call to a member function getShowSwatchTooltip() on null
    – HaFiz Umer
    Oct 7, 2021 at 11:51

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.