cancel
Showing results for 
Search instead for 
Did you mean: 

Get Attribute options by Attribute ID not working

SOLVED

Get Attribute options by Attribute ID not working

How can we get all the possible options for an attribute by attribute id?

 

I tried this but getting an empty data:

protected $optionFactory;

protected $_attributeOptionCollection;

public function __construct(
  \Magento\Eav\Api\Data\AttributeOptionInterfaceFactory $optionFactory,
  \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection $attributeOptionCollection
){
    $this->optionFactory = $optionFactory;
    $this->_attributeOptionCollection = $attributeOptionCollection;
}
$optionValue = 53; // your attribute value
$optionFactory = $this->optionFactory->create();
$optionFactory->load($optionValue); // load by option value
$attributeId = $optionFactory->getAttributeId(); // atribute id of given option value
$optionData = $this->_attributeOptionCollection
                ->setPositionOrder('asc')
                ->setAttributeFilter($attributeId)
                ->setIdFilter($optionValue)
                ->setStoreFilter()
                ->load(); // load option data by attribute id and given option value
echo "<pre>"; print_r($optionData->getData()); exit;
1 ACCEPTED SOLUTION

Accepted Solutions

Re: Get Attribute options by Attribute ID not working

Hello @tvgarden,

 

Please check below code and I have created sample code of color attribute, you can replace with your attribute

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require 'app/bootstrap.php';

$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
$app = $bootstrap->createApplication('Magento\Framework\App\Http');
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$objectManager->get('Magento\Framework\App\State')->setAreaCode('frontend'); // adminhtml

$eavConfig = $objectManager->create('\Magento\Eav\Model\Config');

$attributeCode = 'color';
$attribute = $eavConfig->getAttribute('catalog_product', $attributeCode);
$options = $attribute->getSource()->getAllOptions();
print '<pre>';
print_r($options);
// $bootstrap->run($app);

You can also check result https://www.screencast.com/t/o6veC3NT43

 

--
If my answer is useful, please Accept as Solution & give Kudos

View solution in original post

6 REPLIES 6

Re: Get Attribute options by Attribute ID not working

Hello @tvgarden

 

Using Dependency Injection (DI)

 

  • \Magento\Eav\Model\Entity\Attribute
  • \Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection
  • \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection

Sample File Path: app/code/YourCompanyName/YourModuleName/Block/YourCustomBlock.php

 
<?php
namespace YourCompanyName\YourModuleName\Block;
 
class YourCustomBlock extends \Magento\Framework\View\Element\Template {
  
    /**
     * @var \Magento\Eav\Model\Entity\Attribute
     */
    protected $_entityAttribute;
 
    /**
     * @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection
     */
    protected $_entityAttributeCollection;
  
    /**
     * @var \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection
     */
    protected $_entityAttributeOptionCollection;
  
    /**
     * @param \Magento\Framework\View\Element\Template\Context $context
     * @param \Magento\Eav\Model\Entity\Attribute $entityAttribute
     * @param \Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection $eavEntityAttributeCollection 
     * @param \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection $entityAttributeOptionCollection
     * @param array $data
     */
    public function __construct(
        \Magento\Framework\View\Element\Template\Context $context,
        \Magento\Eav\Model\Entity\Attribute $entityAttribute,
        \Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection $entityAttributeCollection, 
        \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection $entityAttributeOptionCollection,
        array $data = []
    ) {
        $this->_entityAttribute = $entityAttribute;
        $this->_entityAttributeCollection = $entityAttributeCollection; 
        $this->_entityAttributeOptionCollection = $entityAttributeOptionCollection;
  
        parent::__construct($context, $data);
    }
 
    /**
     * Get attribute info by attribute code and entity type
     *
     * @param mixed $entityType can be integer, string, or instance of class Mage\Eav\Model\Entity\Type
     * @param string $attributeCode
     * @return \Magento\Eav\Model\Entity\Attribute
     */
    public function getAttributeInfo($entityType, $attributeCode)
    {
        return $this->_entityAttribute->loadByCode($entityType, $attributeCode);
    }
  
    /**
     * Get all options name and value of the attribute
     *
     * @param int $attributeId
     * @return \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection
     */
    public function getAttributeOptionAll($attributeId)
    {
        return $this->_attributeOptionCollection
                    ->setPositionOrder('asc')
                    ->setAttributeFilter($attributeId)
                    ->setStoreFilter()
                    ->load();
    }
  
    /**
     * Get particular option's name and value of the attribute
     *
     * @param int $attributeId
     * @param int $optionId
     * @return \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection
     */
    public function getAttributeOptionById($attributeId, $optionId)
    {
        return $this->_attributeOptionCollection
                    ->setPositionOrder('asc')
                    ->setAttributeFilter($attributeId)
                    ->setIdFilter($optionId)
                    ->setStoreFilter()
                    ->load();
    }
 
    /**
     * Get the first option's name and value of the attribute
     *
     * @param int $attributeId
     * @return \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection
     */
    public function getAttributeFirstOption($attributeId)
    {
        return $this->_attributeOptionCollection
                    ->setPositionOrder('asc')
                    ->setAttributeFilter($attributeId)
                    ->load()
                    ->getFirstItem();
    } 
}
Now, we can use the functions in our view (.phtml) file as follows. Here, we will be fetching attribute data for attribute “style_bags”.
 
$attributeCode = 'style_bags';
$entityType = 'catalog_product';
  
$attributeInfo = $block->getAttributeInfo($entityType, $attributeCode);
var_dump($attributeInfo->getData());
  
$attributeId = $attributeInfo->getAttributeId();
$optionId = 26;
  
$attributeOptionAll = $block->getAttributeOptionAll($attributeId);
var_dump($attributeOptionAll->getData());
  
$attributeOptionSingle = $block->getAttributeOptionById($attributeId, $optionId);
var_dump($attributeOptionSingle->getData());
 
$attributeOptionSingle = $block->getAttributeFirstOption($attributeId);
var_dump($attributeOptionSingle->getData());
Using Object Manager
 
/**
 * Get attribute info by attribute code and entity type
 */
$attributeCode = 'style_bags';
$entityType = 'catalog_product';
  
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
  
$attributeInfo = $objectManager->get(\Magento\Eav\Model\Entity\Attribute::class)
                               ->loadByCode($entityType, $attributeCode);
  
var_dump($attributeInfo->getData());
  
/**
 * Get all options name and value of the attribute
 */
$attributeId = $attributeInfo->getAttributeId();
$attributeOptionAll = $objectManager->get(\Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection::class)
                                    ->setPositionOrder('asc')
                                    ->setAttributeFilter($attributeId)
                                    ->setStoreFilter()
                                    ->load();
  
var_dump($attributeOptionAll->getData());
  
/**
 * Get particular option's name and value of the attribute
 */
$optionId = 26; 
$attributeOptionSingle = $objectManager->get(\Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection::class)
                                       ->setPositionOrder('asc')
                                       ->setAttributeFilter($attributeId)
                                       ->setIdFilter($optionId)
                                       ->setStoreFilter()
                                       ->load();
  
var_dump($attributeOptionSingle->getData());
 
/**
 * Get the first option's name and value of the attribute
 */
$attributeOptionSingle = $objectManager->get(\Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection::class)
                                       ->setPositionOrder('asc')
                                       ->setAttributeFilter($attributeId)
                                       ->setStoreFilter()
                                       ->load()
                                       ->getFirstItem();
  
var_dump($attributeOptionSingle->getData());
Cheers Smiley Happy
Manish Mittal
https://www.manishmittal.com/

Re: Get Attribute options by Attribute ID not working

Hello @tvgarden,

 

Please check below code and I have created sample code of color attribute, you can replace with your attribute

<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require 'app/bootstrap.php';

$bootstrap = \Magento\Framework\App\Bootstrap::create(BP, $_SERVER);
$app = $bootstrap->createApplication('Magento\Framework\App\Http');
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$objectManager->get('Magento\Framework\App\State')->setAreaCode('frontend'); // adminhtml

$eavConfig = $objectManager->create('\Magento\Eav\Model\Config');

$attributeCode = 'color';
$attribute = $eavConfig->getAttribute('catalog_product', $attributeCode);
$options = $attribute->getSource()->getAllOptions();
print '<pre>';
print_r($options);
// $bootstrap->run($app);

You can also check result https://www.screencast.com/t/o6veC3NT43

 

--
If my answer is useful, please Accept as Solution & give Kudos

Re: Get Attribute options by Attribute ID not working

Hello @Manish Mittal,

 

Thank you for your reply.

 

I tried the first solution but it's returning an empty array. 

At the moment I hard coded the attribute id for 'color'.

This code is called by ajax.

 

<?php

namespace Vendor\Module\Controller\Adminhtml\Index;

class Customajax extends \Magento\Backend\App\Action
{
    protected $resultPageFactory;
    protected $resultJsonFactory;
    protected $attribute_id;
    protected $optionFactory;
    protected $_attributeOptionCollection;
    protected $_productAttributeRepository;

    public function __construct(




        \Magento\Backend\App\Action\Context $context,
        \Magento\Framework\Controller\Result\JsonFactory $resultPageFactory,
        \Magento\Framework\Controller\Result\JsonFactory $resultJsonFactory,
          \Magento\Eav\Api\Data\AttributeOptionInterfaceFactory $optionFactory,
  \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection $attributeOptionCollection,
       \Magento\Catalog\Model\Product\Attribute\Repository $productAttributeRepository ,
         \Magento\Eav\Model\Entity\Attribute $entityAttribute,
        \Magento\Eav\Model\ResourceModel\Entity\Attribute\Collection $entityAttributeCollection, 
        \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection $entityAttributeOptionCollection,
          array $data = []




    ) {
   
        parent::__construct($context);
        $this->resultPageFactory = $resultPageFactory;
         $this->resultJsonFactory = $resultJsonFactory;
                  $this->optionFactory = $optionFactory;
    $this->_attributeOptionCollection = $attributeOptionCollection;
     $this->_productAttributeRepository = $productAttributeRepository;

         $this->_entityAttribute = $entityAttribute;
        $this->_entityAttributeCollection = $entityAttributeCollection; 
        $this->_entityAttributeOptionCollection = $entityAttributeOptionCollection;
        /*

    */
    }

    public function execute()
    {
        if($this->getRequest()->isAjax()){
         
     $this->attribute_id = $this->getRequest()->getParam('value'); 
      

         $array = $this->getArray();
         return  $this->resultJsonFactory->create()->setData(['message' => 'hi', 'value' => $this->attribute_id, 'array' => $array]);
        }

         return  $this->resultJsonFactory->create();
    }


    public function getArray(){

// This hard coded array works
    $array = array(
      array("value"=>"1","label"=>"Value 1","labeltitle"=>"value 1"),
      array("value"=>"2","label"=>"Value 1","labeltitle"=>"value 1"),
      array("value"=>"3","label"=>"Value 1","labeltitle"=>"value 1")
    );
    
// I would like this code to work
//For testing purpose I hard coded attribute_id 
$array = $this->getAttributeOptionAll(93);

     return   $array;
    }




 /**
     * Get all options name and value of the attribute
     *
     * @param int $attributeId
     * @return \Magento\Eav\Model\ResourceModel\Entity\Attribute\Option\Collection
     */
    public function getAttributeOptionAll($attributeId)
    {
        return $this->_attributeOptionCollection
                    ->setPositionOrder('asc')
                    ->setAttributeFilter($attributeId)
                    ->setStoreFilter()
                    ->load();
    }
 
}

 

Re: Get Attribute options by Attribute ID not working

@tvgarden

 

It works now? or still facing issue?

Manish Mittal
https://www.manishmittal.com/

Re: Get Attribute options by Attribute ID not working

hi @Manish Mittal

I have tried the first solution from yours, it was returning an empty array.

Re: Get Attribute options by Attribute ID not working

hi @gelanivishal

 

I used attribute_id and it works without problems.

Thank you very much for your reply.