Magento 2 – How to Get Value from Attribute from Store ID 0 (Admin/Unique)

attribute-optionsattributesmagento2product-attribute

I'm trying to get store label for admin (store 0 – zero) but since I have something in "Default Store Label" I'm getting only that value. I need to find the solution to get always only the admin (unique) value. If solution will be like override/plugin for core – that will be applicable too.

Code which I'm using:

//($this->attributeOptionManagement = \Magento\Eav\Api\AttributeOptionManagementInterface)

$existingOptions = $this->attributeOptionManagement->getItems(Product::ENTITY, $attributeCode);
foreach ($existingOptions as $existingOption) {
    $this->existingOptions[$attributeCode][] = $existingOption->getLabel();
}

So if I have this:

enter image description here

I will have this output based on my code:

Array
(
    [0] =>  
    [1] => Black
    [2] => Charcoal
    [3] => Cream
    [4] => Gray
    [5] => Green
    [6] => Lightning
    [7] => Natural
    [8] => Olive
)

And if I have this:

enter image description here

The output will be like that:

Array
(
    [0] =>  
    [1] => BLACK
    [2] => CHARC
    [3] => CRBBL
    [4] => GR/NA
    [5] => GYCHR
    [6] => LTHTG
    [7] => NATUR
    [8] => OLIVE
)

Best Answer

I have tried this code and it works fine for me:

<?php
    $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
    $eavConfig = $objectManager->get('\Magento\Eav\Model\Config');
    $attribute = $eavConfig->getAttribute('catalog_product', 'color')->setStoreId(0);
    $options = $attribute->getSource()->getAllOptions();
    foreach ($options as $existingOption) {
        echo $existingOption['label'];
    }
?>

Can you inject the class \Magento\Eav\Model\Config and try this solution. Above code is tested. Also you can try the below code but its not tested.

$existingOptions = $this->attributeOptionManagement->getItems(Product::ENTITY, $attributeCode)->setStoreId(0);
Related Topic