0

I am passing attribute id in my controller's URL and I am taking that id as below in my controller,

$colorparam =$this->getRequest()->getParams('color');

This returns me the id present in the controller. Now, I want the label or say it's an option from this id without using any product instance.

For example: I have attribute id -50 but I want it's label as Red.

I want to get this without loading any specific product in my controller.

2
  • You want to get attribute label or attribute option label here ? Nov 13 '19 at 7:37
  • I want attribute option by it's value in my custom controller.
    – chanchal
    Nov 13 '19 at 7:51
1

You can use this in your controller file

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

public function execute()
{
    $optionValue = 50;
    $optionFactory = $this->optionFactory->create();
    $optionFactory->load($optionValue);
    $attributeId = $optionFactory->getAttributeId();
    $optionData = $this->_attributeOptionCollection
                    ->setPositionOrder('asc')
                    ->setAttributeFilter($attributeId)
                    ->setIdFilter($optionValue)
                    ->setStoreFilter()
                    ->load();
    echo "<pre>"; print_r($optionData->getFirstItem()->getValue()); exit;
}

Hope this will help you!

4
  • Hi, The last line $optionData->getData() is giving me all data. I just want value.
    – chanchal
    Nov 13 '19 at 9:17
  • Can you please use this ? $optionData->getFirstItem()->getValue() Nov 13 '19 at 9:24
  • I've updated code in answer as well. Nov 13 '19 at 9:25
  • Thanks Buddy. Happy to help you :) Nov 13 '19 at 10:20
0

Run this below script from your root folder :

<?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\ResourceModel\Entity\Attribute\Option\Collection');

$attributeId = 93;
$attribute = $eavConfig
    ->setPositionOrder('asc')
    ->setAttributeFilter($attributeId)
    ->setStoreFilter()
    ->load();
foreach ($attribute as $key => $value) {
    echo $value['value'] . "<br/>";
}
exit;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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