0

I have created customer custom attribute 'segments' with the below options:

Options: SME, Reseller, Others

I want get segments value with text based on the customer id in magento2.

How to achieve this.

Thanks in Advance :-)

2 Answers 2

0

You can get value and text by using this code:

<?php

$customerId = 12;
$objectManager = \Magento\Framework\App\ObjectManager::getInstance();
$customer = $objectManager->create('Magento\Customer\Model\Customer')->load($customerId);

//Get segments value
$segmentsValue = $customer->getCustomAttributeText('segments')->getValue();

//Get segments text
$segmentsText = $customer->getResource()
->getAttribute('segments')
    ->getSource()
        ->getOptionText($customer->getData('segments'));

echo $segmentsText;
1
  • Is this a Magento 2 solution? I got Call to undefined method Magento\Customer\Model\Data\Customer::getCustomAttributeText() Commented Feb 16, 2022 at 15:30
0

This should work.

protected $_customerSession;

public function __construct(
    \Magento\Customer\Model\Session $customerSession
) {
    $this->_customerSession = $customerSession;
}

public function getMyAttibuteValue() {
    $optionId = $this->_customerSession->getCustomer()->getSegments();
    $attribute = $this->_customerSession->getCustomer()->getResource()->getAttribute('segments');
    if ($attribute->usesSource()) {
        $myAttributeValue = $attribute->getSource()->getOptionText($optionId);
    }
}

Your Answer

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

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