1

I know I can do the following

    $customerId = 1;
    $customer = $this->customerRepositoryInterface->getById($customerId);
    $code = $customer->getCustomAttribute('attribute_code')->getValue();

But as the attribute is a type of "select" and not "text", it gives me the ID as the value and not the actual label

Therefore how do I get the label/frontend name of the option instead of the ID

2

2 Answers 2

0

You might need to load the attribute using the AttributeRepositoryInterface::get($entityTypeCode, $attributeCode).

This will return an AttributeInterface on which you can call getOptions().

This will return an AttributeOptionInterface[]

Each AttributeOptionInterface exposes getLabel() and getValue().

What you are left with is a search problem.

Also as this is a custom attribute you(or who added the attribute) in a DataPatch or InstallScript, probably already specified the options for it. From that Option class you can extract your label based on your value.

0

You need to use the EAV config model to retrieve this information. Add the \Magento\Eav\Model\Config to your constructor and you can use the following snippet to get your value.

protected $_eavConfig;

public function __construct(... \Magento\Eav\Model\Config $eavConfig ...) {
...
$this->_eavConfig = $eavConfig;
...
}

public function getAttributeLabelByValue($attributeCode, $entityType, $value) {
    try {
        $entityType = $this->_eavConfig->getEntityType($entityType);
        $attribute  = $this->_eavConfig->getAttribute($entityType, $attributeCode);
        $options    = $attribute->getSource()->getAllOptions();
        foreach ($options as $option) {
            if ($option['value'] == $value) {
                return $option['label'];
            }
        }
    }
    catch (\Exception $e) {
        return null;
    }

    return null;
}

Where $value is whatever getCustomAttribute('attribute_code')->getValue() returns and where $entityType is "customer" or "catalog_product" or any other "eav_entity_code" from the "eav_entity_type" database table

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

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