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