Magento2: get custom customer attribute value

Custom attributes can also be obtained using getData() method.

Below example fetches a customer custom attribute, custom_attribute_name, in an observer.


namespace Company\Module\Observer;
use Magento\Framework\Event\ObserverInterface;
use Magento\Framework\Event\Observer;
use Magento\Customer\Api\CustomerRepositoryInterface;

class EnablePaymentMethodByCustomerAttribute implements ObserverInterface{
/** @var CustomerRepositoryInterface */
protected $_customerRepository;
protected $_logger;
 * 
 * @param CustomerRepositoryInterface $customerRepository
 * @param \Psr\Log\LoggerInterface $logger
 */
public function __construct(
    CustomerRepositoryInterface $customerRepository,
    \Psr\Log\LoggerInterface $logger
)
{
    $this->_customerRepository = $customerRepository;
    $this->_logger = $logger;
}

/**
 * 
 * @param Observer $observer
 */
public function execute(Observer $observer)
{
    $customer = $observer->getCustomer();
    $customer->getData('custom_attribute_name');
}

}

Leave a comment

Your email address will not be published. Required fields are marked *