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

Today, we’re going to teach you how to check if an attribute is swatch attribute in Magento 2.

Now, there are multiple types of attribute we can create in Magento 2 such as text, swatch, multiple select, price, dropdown, etc.

And to check the attribute type of any specific attribute, you need to know either its attribute ID or attribute code.

Steps to Check if an Attribute is Swatch Attribute or Not

Here is the simple, step-by-step process to find out whether an attribute is a swatch or not.

The first step of the process is to create a block file IsSwatchAttribute.php in app/code/MD/CheckAttribute/Block/ directory and copy the following code into the file.

<?php
/**
* Created By : MageDelight Pvt. Ltd.
 */
namespace MD\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);
    }
}

As you can see in the above code, the getAttribute() in the isSwatchAttr() function we need to set eav_entity_type in the 1st parameter and attribute_code in the 2nd parameter.

Once you’ve done that, then you need to use the following function in the phtml file:

echo $block->isSwatchAttr();

The return type of the above function is Boolean, so you will get the output as either a Yes or No.

Concluding Words…

And there you have it!

This is how easy it is to check if an attribute is swatch attribute or not in Magento 2.

We hope that you found this tutorial helpful. If you have any doubts, please ask them in the comments below. And in case you need our professional assistance, feel free to contact us anytime.