2

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

}

1 Answer 1

5

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;

?>
2
  • thank you for reply, how can I get the original image ? Jun 5, 2017 at 14:05
  • what is optionIdvalue? Nov 29, 2019 at 12:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.