Magento – How to get visual swatch image from attribute_id

attributesmagento-2.1swatches

I want to get the visual swatch image from attribute_id, but I could not find how to get it.

I want to get swatch image in getBrand() method, I have got attribute_id and attribute_option_id.

<?php

namespace Vendor\Catalog\Helper;

use Magento\Catalog\Model\Product as ModelProduct;
use Magento\Store\Model\Store;
use Magento\Swatches\Helper\Data;

class Brand extends \Magento\Framework\App\Helper\AbstractHelper
{
    /**
     * @var TimezoneInterface
     */
    protected $_swatchesHelper;
    protected $_brandAttributeCode = 'brand';

    public function __construct(
        \Magento\Framework\App\Helper\Context $context,
        Data $swatchesHelper
    ) {
        $this->_swatchesHelper = $swatchesHelper;
        parent::__construct($context);
    }

    public function getBrand(ModelProduct $product){
        $attribute = $product->getResource()->getAttribute($this->_brandAttributeCode);
        //$attribute->getId();
        $label = $attribute->getFrontend()->getLabel($product);
        $attrValue = $attribute->getFrontend()->getValue($product);

        $attributeOptionIds = $attribute->getSource()->getOptionId($attrValue);

        //$swatch = $this->_swatchesHelper->getSwatchesByOptionsId($attributeOptionIds);

        if(strtolower($attrValue) != 'no' && $attrValue !='' && $attrValue !== 0){
            return array('name' => $attrValue, 'label' => $label, 'image' => '????'); 
        }
        return false;    
    } 

    public function getBrandHtml(ModelProduct $product){
        $brand = $this->getBrand($product);
        if($brand){
            return '<img src="'. $brand['image'] .'" alt="'.$brand['label'].':'.$brand['code'].'">';
        }
        return '';
    }

}

Best Answer

Use Below code to get swatch image.

<?php

$objectManager = \Magento\Framework\App\ObjectManager::getInstance();

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

exit;

?>
Related Topic