Reading list Switch to dark mode

    How to get all the options of a custom attribute in magento 2

    Updated 16 July 2021

    Today I will share with you that How you can get all the options of a custom attribute by the attribute code in Magento 2.

    First of all, you need to create an instance of EavConfig. I have shared the code that I used in a controller file, but you can use it in Helper or block according to your need.

    <?php
    namespace Companyname\Modulename\Controller\Product;
    
    use Magento\Framework\App\Action\Context;
    
    class Control extends \Magento\Framework\App\Action\Action
    {
        protected $eavConfig;
       
        public function __construct(
            Context $context,
            \Magento\Eav\Model\Config $eavConfig
        ) {
            $this->_eavConfig = $eavConfig;
            parent::__construct($context);
        }
    }

    after that, write the function to get the all the options of the attribute,

    public function execute()
    	{
    		$attributeCode = "attribute_code";
    		$attribute = $this->_eavConfig->getAttribute('catalog_product', $attributeCode);
    		$options = $attribute->getSource()->getAllOptions();
    		$arr = [];
    		foreach ($options as $option) {
    		    if ($option['value'] > 0) {
    		        $arr[] = $option;
    		    }
    		}
      	}

    $arr now contains all the options as you can see below. The “value” is the option id and “label” is the frontend label of the option.

    Array
    (
        [0] => Array
            (
                [value] => 280
                [label] => option1
            )
    
        [1] => Array
            (
                [value] => 281
                [label] => option2
            )
    
        [2] => Array
            (
                [value] => 282
                [label] => option3
            )
    
        [3] => Array
            (
                [value] => 283
                [label] => option4
            )
    )

    You can use this wherever you need to display options of a custom attribute. I have used this on Magento version 2.2.1 but this will work for other versions as well.

    Searching for an experienced
    Magento 2 Company ?
    Find out More

    For any queries, you can comment below.

    . . .

    Leave a Comment

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


    Be the first to comment.

    Back to Top

    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home