Magento, Magento 2

How to Check if Attribute is Swatch Attribute in Magento 2?

How to Check if Attribute is Swatch Attribute in Magento 2

In this tutorial, We will learn about how to check if the attribute is swatch attribute or not in Magento 2. There are many types of attribute we can create in Magento 2. For example, Dropdown, text, swatch, Multiple Select, Price, etc. Sometimes, We need to check attribute type by attribute code or attribute id. So, how can we check If we need to check the attribute is swatch attribute or not in Magento 2.

Let’s create a block function for check attribute is swatch attribute or not.

You may also like this :

First of all, Create a block file IsSwatchAttribute.php at app/code/RH/CheckAttribute/Block/ and paste the below code :


<?php
/**
 * Created By : Rohan Hapani
 */
namespace RH\CheckAttribute\Block;

class IsSwatchAttribute extends \Magento\Framework\View\Element\Template {
    /**
     * @var \Magento\Eav\Model\Config
     */
    protected $eavConfig;

    /**
     * @var \Magento\Swatches\Helper\Data
     */
    protected $swatchHelper;

    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Eav\Model\Config                        $eavConfig
     * @param \Magento\Swatches\Helper\Data                    $swatchHelper
     * @param array                                            $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Eav\Model\Config $eavConfig,
        \Magento\Swatches\Helper\Data $swatchHelper,
        array $data = []
    ) {
        $this->eavConfig = $eavConfig;
        $this->swatchHelper = $swatchHelper;
        parent::__construct($context, $data);
    }

    public function isSwatchAttr()
    {
        $attribute = $this->eavConfig->getAttribute('catalog_product', 'color');
        return $this->swatchHelper->isSwatchAttribute($attribute);
    }
}

Here, in isSwatchAttr() function you can see that in getAttribute() we need to set eav_entity_type in first parameter and attribute_code in second parameter.

Then, you can use this function in your phtml file like this below way :


echo $block->isSwatchAttr();

Its return type is Boolean (True/false). So, you will get the output as a boolean type.

I hope this blog will helpful for easily understand how to Check if Attribute is Swatch Attribute in Magento 2. In case, I missed anything or need to add some information, always feel free to leave a comment in this blog, I’ll get back with proper solution 🙂

Tagged ,