Getting Visual Swatchs on Phtml file for products

Viewing the visual swatches for the simple products in PLP and PDP pages .

This is custom functionility to make the simple product to config by addin the related products with same property but with different color,size and attributes.



$swatchHelper=$this->_objectManager->get("Magento\Swatches\Helper\Media");
$swatchCollection = $this->_objectManager->create('Magento\Swatches\Model\ResourceModel\Swatch\Collection');
// brand logo is my Visual Swatch attribute 
$optionIdvalue=$this->getProduct()->getBrandLogo(); 
$swatchCollection->addFieldtoFilter('option_id',$optionIdvalue);
$item=$swatchCollection->getFirstItem();
echo $swatchHelper->getSwatchAttributeImage('swatch_thumb', $item->getValue());
echo $swatchHelper->getSwatchAttributeImage('swatch_image', $item->getValue());

Here it is done with a object but always convert the object manager to a block based on the object manager repos.

        <?php
        $relatedProducts = $_product->getRelatedProducts();?>
        <?php
        if (!empty($relatedProducts)):
        foreach ($relatedProducts as $relatedProduct):
        $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
        $relproduct = $objectManager->create('Magento\Catalog\Model\Product')->load($relatedProduct->getId());
        $subattribute = $relproduct->getData("$primaryattribute");
        $optionIdvalue = $subattribute;
        $swatchCollection = $objectManager->create('Magento\Swatches\Model\ResourceModel\Swatch\Collection');
         $swatchCollection->addFieldtoFilter('option_id',$optionIdvalue);
        $item=$swatchCollection->getFirstItem();
        $thumb = $swatchHelper->getSwatchAttributeImage('swatch_image', $item->getValue());
        $label = $relproduct->getAttributeText("$primaryattribute");
        if($thumb):
        ?>
        <div class="attributesection">
            <div class="swatch_img"><a class="relproduct" href="<?= $escaper->escapeUrl($relproduct->getProductUrl()) ?>">
                <div class="swatch_img_field" style="height:25px;width:25px;background-image:url(<?=$thumb?>);background-repeat: no-repeat;background-position: center;"></div>
            </a>
        </div>
    </div>




Leave a comment

Your email address will not be published. Required fields are marked *