Frage

magento 2 I would like to get an attribute option label by attribute option id.

For Example:-

attribute option value : 53,

attribute option label/text/name : green

from the above scenario i want to get attribute option label/text/name.

Note: without loading product i need to get this. please suggest me.

War es hilfreich?

Lösung

You need to add following in your __construct method

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

Now you can get option data using option value;

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

Andere Tipps

Try the following code:

$_optionId = '53';
$_attributeId = $_product->getResource()->getAttribute('color');
if ($_attributeId->usesSource()) {
      $_optionText = $_attributeId->getSource()->getOptionText($_optionId);
}

Try the below code:

$option_id = 5431;
$attribute_code = 'coffee_type';
$objectManager =  \Magento\Framework\App\ObjectManager::getInstance();

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

    $attribute = $eavConfig->getAttribute('catalog_product', $attribute_code);
    $optionlabel =  $attribute->getSource()->getOptionText($option_id);

Try the following code to get option label by option Id directly from the database.

$resource = $objectManager->get('Magento\Framework\App\ResourceConnection');
$connection = $resource->getConnection();
$tableName = $resource->getTableName('eav_attribute_option_value');

$option_id = 350;
$sql = "select * FROM " . $tableName . " where option_id=".$option_id;
$result = $connection->fetchAll($sql);

echo $option_label = $result[0]['value'];

Happy coding :)

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit magento.stackexchange
scroll top