3

I added related products list in product details page. I see there all related products list are display but now i need to display swatches in this list. How can it possible for related products list.

If any one know please give me answers.

4 Answers 4

13

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>
11
  • I am not getting proper selected options array why ? Commented Sep 24, 2018 at 13:56
  • above code only brings a options in related product list. -> to get selected option array in post you have create 2D array like $option[1][141] =red , here 1 is product id And 141 is attribute id of color. Commented Sep 25, 2018 at 3:50
  • Worked perfectly Thanks you so much. :)
    – Ask Xah
    Commented Aug 3, 2019 at 11:32
  • Only the color swatches are showing after applying this. Nothing happened after clicking on swatches. Commented Feb 5, 2020 at 9:34
  • 1
    Hello, I used above mentioned code in Magento2.4 to display swatches in related product but getting below error. Error: Call to a member function getShowSwatchTooltip() on null. Can anyone please guide me on this?
    – Arjun
    Commented Oct 9, 2020 at 4:42
6

In 2.2.5 we're doing the following to achieve the swatches, essentially it replicates the code from the Mage_Catalog::product/list.phtml template where swatches are by default.

Firstly you need to add the swatch renderers to the block via the layout XML for the catalog_product_view layout handle.

In app/design/frontend/MyCompany/mytheme/Magento_Swatches/layout/catalog_product_view.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="catalog.product.related">
            <block class="Magento\Framework\View\Element\RendererList" name="related.product.type.details.renderers" as="details.renderers">
                <block class="Magento\Framework\View\Element\Template" as="default"/>
                <block class="Magento\Swatches\Block\Product\Renderer\Listing\Configurable" as="configurable" template="Magento_Swatches::product/listing/renderer.phtml" />
            </block>
        </referenceBlock>
    </body>
</page>

Then override the Magneto_Catalog::product/list/items.phtml file by creating your own in app/design/frontend/MyCompany/mytheme/Magento_Catalog/templates/product/list/items.phtml with the below modifications:

  1. Just below the opening PHP tags use Magento\Framework\App\Action\Action;

  2. Load the post data and json helpers just before the main switch:

    $postDataHelper = $this->helper('Magento\Framework\Data\Helper\PostHelper');
    $jsonHelper = $this->helper('Magento\Framework\Json\Helper\Data');
    
  3. Replace the add to cart method, adding the form so product can be added via AJAX inside your product actions:

    <?php if ($_item->isSaleable()): ?>
        <?php
            $postData = $postDataHelper->getPostData($block->getAddToCartUrl($_item), ['product' => $_item->getEntityId()]);
            $postParams = $jsonHelper->jsonDecode($postData);
        ?>
        <form data-role="tocart-form" data-product-sku="<?= $block->escapeHtml($_item->getSku()) ?>" action="<?= /* @NoEscape */ $postParams['action'] ?>" method="post">
            <input type="hidden" name="product" value="<?= /* @escapeNotVerified */ $postParams['data']['product'] ?>">
            <input type="hidden" name="<?= /* @escapeNotVerified */ Action::PARAM_NAME_URL_ENCODED ?>" value="<?= /* @escapeNotVerified */ $postParams['data'][Action::PARAM_NAME_URL_ENCODED] ?>">
            <?= $block->getBlockHtml('formkey') ?>
            <button type="submit"
                    title="<?= $block->escapeHtml(__('Add to Cart')) ?>"
                    class="action tocart primary">
                <span><?= /* @escapeNotVerified */ __('Add to Cart') ?></span>
            </button>
        </form>
    <?php endif; ?>
    
  4. Then just before the closing if statement add the JS to not redirect to cart if the config for it is disabled:

      <?php if (!$block->isRedirectToCartEnabled()) : ?>
            <script type="text/x-magento-init">
            {
                "[data-role=tocart-form], .form.map.checkout": {
                    "catalogAddToCart": {
                        "product_sku": "<?= /* @NoEscape */ $_item->getSku() ?>"
                    }
                }
            }
            </script>
        <?php endif; ?>
    

In the end you should see swatches being rendered and able to add products via AJAX.

2
  • Is it possible to do this same thing with crosssell's on the product detail page? I have created the block inside of the Product Detail Page, and the crosssell products are now showing up appropriately, but I can't seem to get the swatches to render. I think it is because I need to change the catalog_product_view.xml referenceBlock.
    – Scrivvles
    Commented Jul 31, 2018 at 20:42
  • It doesn't work for me. Color swatches are not visible. Commented Feb 5, 2020 at 9:28
4

To display Swatches along with the product name, thumbnail, etc, just like on the Category product lists, I did this in my Theme:

  1. Create this file:

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

Add this content (almost the same as the catalog_category_view one), so the Swatch renderer template is available on the Product View page:

<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="related.product.type.details.renderers">
        <block class="Magento\Swatches\Block\Product\Renderer\Listing\Configurable" as="configurable" template="Magento_Swatches::product/listing/renderer.phtml" ifconfig="catalog/frontend/show_swatches_in_product_list" />
    </referenceBlock>
  </body>
</page>
  1. In this file:

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

Add the related.product.type.details.renderers to the catalog.product.related` , like so:

<block class="Magento\Catalog\Block\Product\ProductList\Related" name="catalog.product.related" template="Magento_Catalog::product/list/items.phtml" group="detailed_info">
    <block class="Magento\Framework\View\Element\RendererList" name="related.product.type.details.renderers" as="details.renderers">
        <block class="Magento\Framework\View\Element\Template" as="default"/>
     </block>
</block>
  1. Then update the items.phtml template:

app/design/frontend/MyCompany/mytheme/Magento_Catalog/templates/product/list/items.phtml

And echo the getProductDetailsHtml() output where you want. For instance:

<div class="product details product-item-details">
  <?php echo $block->getProductDetailsHtml($_item); ?>
  ...
</div>
1
  • It doesn't work for me. After applying this whole related block disappear. Commented Feb 5, 2020 at 9:36
0
<?php/***********Display Brand Attribute************/?>

            <?php
            if($_product->getManufacturer()){
                $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
                $category = $objectManager->get('Magento\Framework\Registry')->registry('current_category');//get current category

                $brand_value = $_product->getResource()->getAttribute('manufacturer')->getFrontend()->getValue($_product);
                $brand_id = $_product->getManufacturer();
                $curnt_cat_url = $category->getUrl();
                $brandId = '?manufacturer='.$brand_id;

                $om = \Magento\Framework\App\ObjectManager::getInstance();
                $swatchHelper=$om->get("Magento\Swatches\Helper\Media");
                $swatchCollection = $om->create('Magento\Swatches\Model\ResourceModel\Swatch\Collection');
                $swatchCollection->addFieldtoFilter('option_id',$brand_id);
                $item=$swatchCollection->getFirstItem();
                $ThumbImage =  $swatchHelper->getSwatchAttributeImage('swatch_thumb', $item->getValue());
                $SwatchImage = $swatchHelper->getSwatchAttributeImage('swatch_image', $item->getValue());

                ?>

                <div class="brand_bg">
                    <a href="<?php echo $curnt_cat_url.$brandId ?>"><img src="<?php echo $SwatchImage; ?>"></a>
                </div>
            <?php } ?>
            <?php/***********End Brand Attribute************/?>

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.